1

我想知道如何在 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());
    }
}
4

1 回答 1

1

我只是从我的个人代码库中提取大部分内容。它缺少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);

    }
}

这会产生...

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ThisIsTheRootNode>
    <ThisIsAChildNodeOfRoot>
        <ThisIsAChildNode>I Have text!</ThisIsAChildNode>
    </ThisIsAChildNodeOfRoot>
</ThisIsTheRootNode>

一旦你消化了所有这些,我就会通读一遍

于 2012-09-19T02:24:08.760 回答