Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 爪哇及;XML:CRUD_Java_Xml_Crud - Fatal编程技术网

Java 爪哇及;XML:CRUD

Java 爪哇及;XML:CRUD,java,xml,crud,Java,Xml,Crud,我想知道如何在Java中操作XML文件 我知道如何创建和读取,我只是不知道如何更新和删除它们。如果有人知道一个有教程的网站,我将不胜感激。我也想知道如何处理这些记录 以下是我到目前为止的情况: /* * Classe de Lista de Compras */ package xml01; public class ListaCompras { public String descricao; public int quant; public double val

我想知道如何在Java中操作XML文件

我知道如何创建和读取,我只是不知道如何更新和删除它们。如果有人知道一个有教程的网站,我将不胜感激。我也想知道如何处理这些记录

以下是我到目前为止的情况:

/*
 * Classe de Lista de Compras
 */
package xml01;

public class ListaCompras {
    public String descricao;
    public int quant;
    public double valor;
}

package xml01;

import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

public class GravarLer {

    static void gravar(String xml) {
        try {
            FileWriter w = new FileWriter("teste.xml");
            w.write(xml);
            w.close();
        } catch (Exception e) {
            System.out.println("Erro ao gravar XML: " + e);
        }
    }

    static String ler() {
        try {
            Scanner in = new Scanner(new File("testeler.xml"));
            StringBuilder sb = new StringBuilder();
            while (in.hasNext()) {
                sb.append(in.next());
            }
            in.close();
            return sb.toString();
        } catch (Exception e) {
            System.out.println("Erro ao ler XML: " + e);
        }
        return "";
    }
}


/*
 * XStream
 */
package xml01;

import com.thoughtworks.xstream.XStream;

public class Xml01 {

    public static void main(String[] args) {
        // Cria um vetor de registros ListaCompras
        ListaCompras lista[] = new ListaCompras[10];
        // Inicializa os registros com numeros aleatorios
        for (int i = 0; i < lista.length; i++) {
            lista[i] = new ListaCompras();
            lista[i].quant = i + 2000 * i;
            lista[i].valor = i + 0.5 * 11 * i;
        }

        lista[0].descricao = "Arroz";
        lista[1].descricao = "Feijao";
        lista[2].descricao = "Macarrao";
        lista[3].descricao = "Agua mineral";
        lista[4].descricao = "Leite";
        lista[5].descricao = "Pão de forma";
        lista[6].descricao = "Manteiga";
        lista[7].descricao = "Banana";
        lista[8].descricao = "Laranja";
        lista[9].descricao = "Maçã";


        // Inicializa o XStream
        XStream xstream = new XStream();
        // Converte o objeto ListaCompras para XML
        String xml = xstream.toXML(lista);
        // Imprime na tela
        System.out.println(xml);

        // Chamando a classe GravarLer
        GravarLer ClasseGravar = new GravarLer();
        // Chamando o metodo
        GravarLer.gravar(xml);
        // GravarLer.ler();
        // System.out.println(GravarLer.ler());
    }
}
/*
*康帕斯学校
*/
xml01包;
公共类ListaCompras{
公共字符串描述符;
公共信息量;
公众的双重勇气;
}
xml01包;
导入java.io.File;
导入java.io.FileWriter;
导入java.util.Scanner;
公营坟墓工{
静态void gravar(字符串xml){
试一试{
FileWriter w=新的FileWriter(“teste.xml”);
w、 写入(xml);
w、 close();
}捕获(例外e){
System.out.println(“Erro ao gravar XML:+e”);
}
}
静态字符串{
试一试{
Scanner in=new Scanner(新文件(“testeler.xml”);
StringBuilder sb=新的StringBuilder();
while(在.hasNext()中){
某人附加(在下一个()中);
}
in.close();
使某人返回字符串();
}捕获(例外e){
System.out.println(“Erro-aoler-XML:+e);
}
返回“”;
}
}
/*
*XStream
*/
xml01包;
导入com.thoughtworks.xstream.xstream;
公共类Xml01{
公共静态void main(字符串[]args){
//Cria um vetor de registros ListaCompras
ListaCompras lista[]=新ListaCompras[10];
//登记册编号
for(int i=0;i
我只是从我的个人代码库中提取了大部分代码。它缺少xPath,但基本思想就在这里

public final class TestXMLCRUD {

    public static void main(String[] args) {
        new TestXMLCRUD();
    }

    public TestXMLCRUD() {

        try {

            Document doc = createNewDocument();
            setRootNode(doc, "ThisIsTheRootNode");

            Element child = addElement(doc, "ThisIsAChildNodeOfRoot");
            addElement(doc, child, "ThisIsAChildNode", "I Have text!");
            System.out.println(save(doc));

        } catch (TransformerConfigurationException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        } catch (ParserConfigurationException ex) {
            ex.printStackTrace();
        } catch (DOMException ex) {
            ex.printStackTrace();
        }

    }
    private DocumentBuilder builder;

    public Node getRootNode(Document xmlDoc) {

        Node nRoot = null;

        if (xmlDoc != null) {

            nRoot = xmlDoc.getDocumentElement();

        }

        return nRoot;

    }

    public Document createNewDocument() throws ParserConfigurationException {

        Document doc = getDocumentBuilder().newDocument();
        Element root = doc.createElement("root");
        doc.adoptNode(root);
        doc.appendChild(root);

        return doc;

    }

    public Element setRootNode(Document xmlDoc, String name) {

        removeNode(getRootNode(xmlDoc));
        Element root = xmlDoc.createElement(name);
        xmlDoc.adoptNode(root);
        xmlDoc.appendChild(root);

        return root;


    }

    public Document loadDocument(InputStream is) throws ParserConfigurationException, SAXException, IOException {

        return getDocumentBuilder().parse(is);

    }

    public Document loadDocument(File file) throws ParserConfigurationException, SAXException, IOException {

        return getDocumentBuilder().parse(file);

    }

    public Document loadDocumentFromString(String xml) throws ParserConfigurationException, SAXException, IOException {

        Document doc = null;

        ByteArrayInputStream bais = null;

        //StringReader sr = null;
        //InputSource is = null;
        try {

            bais = new ByteArrayInputStream(xml.getBytes());

            doc = loadDocument(bais);

        } finally {

//            try { sr.close(); } catch (Exception e) { }
            try {
                bais.close();
            } catch (Exception e) {
            }

        }

        return doc;

    }

    protected DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {

        if (builder == null) {

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(false); // You might want to change this...
            builder = factory.newDocumentBuilder();

        }

        return builder;

    }

    public Element addElement(Document xmlDoc, String name) {

        Element child = xmlDoc.createElement(name);
        getRootNode(xmlDoc).appendChild(child);

        return child;

    }

    public Node addElement(Document xmlDoc, Node node, String name) {

        Node child = xmlDoc.createElement(name);
        node.appendChild(child);

        return child;

    }

    public Node addElement(Document xmlDoc, Node node, String name, String text) {

        Node child = addElement(xmlDoc, node, name);
        child.setTextContent(text);

        return child;

    }

    public void removeNode(Node parentNode) {

        if (parentNode != null) {

            while (parentNode.hasChildNodes()) {

                removeNode(parentNode.getFirstChild());

            }

            Node parent = parentNode.getParentNode();
            if (parent != null) {

                parent.removeChild(parentNode);

                NodeList childNodes = parent.getChildNodes();
                if (childNodes.getLength() > 0) {

                    List<Node> lstTextNodes = new ArrayList<Node>(childNodes.getLength());
                    for (int index = 0; index < childNodes.getLength(); index++) {

                        Node childNode = childNodes.item(index);
                        if (childNode.getNodeType() == Node.TEXT_NODE) {

                            lstTextNodes.add(childNode);

                        }

                    }

                    for (Node node : lstTextNodes) {

                        removeNode(node);

                    }

                }

            }

        }

    }

    public void save(Document xmlDoc, File fFile) throws TransformerConfigurationException, TransformerException, IOException {

        FileOutputStream fos = null;

        try {

            fos = new FileOutputStream(fFile);
            save(xmlDoc, fos);

            fos.flush();

        } finally {

            try {
                fos.close();
            } catch (Exception e) {
            }

        }

    }

    public void save(Document xmlDoc, OutputStream os) throws TransformerConfigurationException, TransformerException, IOException {

        OutputStreamWriter osw = null;

        try {

            osw = new OutputStreamWriter(os);
            save(xmlDoc, osw);
            osw.flush();

        } finally {

            try {
                osw.close();
            } catch (Exception exp) {
            }

        }

    }

    public String save(Document xmlDoc) throws TransformerConfigurationException, IOException, TransformerException {

        String sValue = null;

        ByteArrayOutputStream baos = null;

        try {

            baos = new ByteArrayOutputStream();
            save(xmlDoc, baos);
            baos.flush();
            sValue = new String(baos.toByteArray());

        } finally {

            try {
                baos.close();
            } catch (Exception exp) {
            }

        }

        return sValue;

    }

    public void save(Document xmlDoc, Writer os) throws TransformerConfigurationException, TransformerException {

        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        tf.setOutputProperty(OutputKeys.METHOD, "xml");
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        DOMSource domSource = new DOMSource(xmlDoc);
        StreamResult sr = new StreamResult(os);
        tf.transform(domSource, sr);

    }
}
公共最终类TestXMLCRUD{
公共静态void main(字符串[]args){
新的TestXMLCRUD();
}
公共TestXMLCRUD(){
试一试{
Document doc=createNewDocument();
setRootNode(文档“ThisIsTheRootNode”);
元素child=addElement(doc,“ThisIsAChildNodeOfRoot”);
addElement(doc,child,“ThisIsAChildNode”,“我有文本!”);
系统输出打印项次(保存(文档));
}捕获(TransformerConfiguration异常ex){
例如printStackTrace();
}捕获(IOEX异常){
例如printStackTrace();
}捕获(TransformerException ex){
例如printStackTrace();
}捕获(ParserConfiguration异常ex){
例如printStackTrace();
}捕获(DomeException除外){
例如printStackTrace();
}
}
私人文档生成器;
公共节点getRootNode(文档xmlDoc){
节点nRoot=null;
如果(xmlDoc!=null){
nRoot=xmlDoc.getDocumentElement();
}
返回nRoot;
}
公共文档createNewDocument()引发ParserConfiguration异常{
Document doc=getDocumentBuilder().newDocument();
元素根=doc.createElement(“根”);
单据节点(根节点);
doc.appendChild(根);
退货单;
}
公共元素setRootNode(文档xmlDoc,字符串名称){
removeNode(getRootNode(xmlDoc));
元素根=xmlDoc.createElement(名称);
xmlDoc.adoptNode(根);
xmlDoc.appendChild(根);
返回根;
}
公共文档loadDocument(InputStream is)抛出ParserConfiguration异常、SAXException、IOException{
返回getDocumentBuilder().parse(is);
}
公共文档loadDocument(文件文件)抛出ParserConfiguration异常、SAXException、IOException{
返回getDocumentBuilder().parse(文件);
}
公共文档loadDocumentFromString(字符串xml)抛出ParserConfiguration异常、SAXException、IOException{
单据单据=空;
ByteArrayInputStream bais=null;
//StringReader sr=null;
//InputSource为空;
试一试{
bais=newbytearrayinputstream(xml.getBytes());
doc=装载文件(BAI);
}最后{
//请尝试{sr.close();}捕获(异常e){}
试一试{
bais.close();
}捕获(例外e){
}
}
退货单;
}
受保护的DocumentBuilder getDocumentBuilder()引发ParserConfiguration异常{
if(builder==null){
DocumentBuilderFactory工厂=DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);//您可能需要更改此。。。
builder=factory.newDocumentBuilder();
}
返回生成器;
}
公共元素addElement(文档xmlDoc,字符串名称){
元素子元素=xmlDoc.createElement(名称);
getRootNode(xmlDoc).appendChild(child);
返回儿童;
}
公共节点addElement(文档xmlDoc、节点节点、字符串名称){
节点子节点=xmlDoc.createElement(n
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ThisIsTheRootNode>
    <ThisIsAChildNodeOfRoot>
        <ThisIsAChildNode>I Have text!</ThisIsAChildNode>
    </ThisIsAChildNodeOfRoot>
</ThisIsTheRootNode>