欢迎访问宙启技术站
智能推送

XML中增、删、改的示例

发布时间:2023-05-14 01:55:06

XML(可扩展标记语言)是一种用于储存和传输数据的结构化标记语言,在Web开发中有着广泛的应用。在XML文档中,标签和元素用于描述和组织数据,而属性用于提供有关元素的附加信息。

本文将介绍XML文档中的三种基本操作——增加、删除和修改元素。我们将结合以下XML示例进行详细解释:

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book id="1">
        <title>《Java编程思想》</title>
        <author>Bruce Eckel</author>
        <price>78.00</price>
    </book>
    <book id="2">
        <title>《深入理解Java虚拟机》</title>
        <author>周志明</author>
        <price>69.00</price>
    </book>
    <book id="3">
        <title>《算法导论》</title>
        <author>Thomas H.Cormen/Charles E.Leiserson/Ronald L.Rivest/Clifford Stein</author>
        <price>89.00</price>
    </book>
</books>

### 增加元素

在XML文档中,可以通过添加新元素来扩展现有结构。我们可以使用DOM(文档对象模型)库或SAX(简单API for XML)解析器将新元素添加到XML文档中。

#### DOM方式

- 创建新元素

当使用DOM方式时,可以使用createElement()方法创建新的元素节点。我们将通过以下示例向XML文档中添加一本新书:

try {
    File file = new File("books.xml");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(file);
            
    // 创建新的元素节点
    Element newBook = doc.createElement("book");
    newBook.setAttribute("id", "4");

    // 创建新的子元素节点
    Element newTitle = doc.createElement("title");
    newTitle.setTextContent("《高性能MySQL》");
    Element newAuthor = doc.createElement("author");
    newAuthor.setTextContent("Baron Schwartz/Peter Zaitsev/Vadim Tkachenko");
    Element newPrice = doc.createElement("price");
    newPrice.setTextContent("98.00");

    // 将子元素节点添加至newBook中
    newBook.appendChild(newTitle);
    newBook.appendChild(newAuthor);
    newBook.appendChild(newPrice);

    // 将newBook添加至根元素books中
    Element root = doc.getDocumentElement();
    root.appendChild(newBook);

    // 更新XML文档
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(file);
    transformer.transform(source, result);
} catch (Exception e) {
    e.printStackTrace();
}

- 结果

添加新书后,XML文档将变为:

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book id="1">
        <title>《Java编程思想》</title>
        <author>Bruce Eckel</author>
        <price>78.00</price>
    </book>
    <book id="2">
        <title>《深入理解Java虚拟机》</title>
        <author>周志明</author>
        <price>69.00</price>
    </book>
    <book id="3">
        <title>《算法导论》</title>
        <author>Thomas H.Cormen/Charles E.Leiserson/Ronald L.Rivest/Clifford Stein</author>
        <price>89.00</price>
    </book>
    <book id="4">
        <title>《高性能MySQL》</title>
        <author>Baron Schwartz/Peter Zaitsev/Vadim Tkachenko</author>
        <price>98.00</price>
    </book>
</books>

#### SAX方式

SAX方式是一种基于事件驱动的解析器。在SAX方式中,我们需要实现自定义的SAX处理器,并定义相应的回调方法。例如,在以下示例中,我们将使用SAX方式向XML文档中添加一本新书:

try {
    File file = new File("books.xml");
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    SAXHandler handler = new SAXHandler();
    parser.parse(file, handler);
    
    // 向XML文档中添加新书
    Book newBook = new Book();
    newBook.setId("4");
    newBook.setTitle("《高性能MySQL》");
    newBook.setAuthor("Baron Schwartz/Peter Zaitsev/Vadim Tkachenko");
    newBook.setPrice("98.00");
    handler.addBook(newBook);

    // 更新XML文档
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(handler.getDocument());
    StreamResult result = new StreamResult(file);
    transformer.transform(source, result);
} catch (Exception e) {
    e.printStackTrace();
}

在SAX方式中,我们将添加新书的逻辑交给了自定义的SAX处理器。在SAXHandler类中,我们需要实现startElement()和endElement()方法来处理XML文档中的元素节点,并实现characters()方法来处理元素节点的文本内容。

class SAXHandler extends DefaultHandler {
    private Document doc;
    private Element root;
    private List<Book> bookList = new ArrayList<>();
    private Book currentBook;

    public void startDocument() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.newDocument();
            root = doc.createElement("books");
            doc.appendChild(root);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startElement(String uri, String localName, String qName, Attributes attributes) {
        if ("book".equals(qName)) {
            currentBook = new Book();
            currentBook.setId(attributes.getValue("id"));
        }
    }

    public void endElement(String uri, String localName, String qName) {
        if ("book".equals(qName)) {
            Element newBook = doc.createElement("book");
            newBook.setAttribute("id", currentBook.getId());

            Element newTitle = doc.createElement("title");
            newTitle.setTextContent(currentBook.getTitle());
            Element newAuthor = doc.createElement("author");
            newAuthor.setTextContent(currentBook.getAuthor());
            Element newPrice = doc.createElement("price");
            newPrice.setTextContent(currentBook.getPrice());

            newBook.appendChild(newTitle);
            newBook.appendChild(newAuthor);
            newBook.appendChild(newPrice);

            root.appendChild(newBook);
            currentBook = null;
        }
    }

    public void characters(char[] ch, int start, int length) {
        String content = new String(ch, start, length).trim();
        if (currentBook != null) {
            switch (qName) {
                case "title":
                    currentBook.setTitle(content);
                    break;
                case "author":
                    currentBook.setAuthor(content);
                    break;
                case "price":
                    currentBook.setPrice(content);
                    break;
            }
        }
    }

    public Document getDocument() {
        return doc;
    }

    public void addBook(Book book) {
        bookList.add(book);
    }
}

- 结果

添加新书后,XML文档将变为:

xml

<?xml version="1.0" encoding="UTF-8"?>

<books>

<book id="1">

<title>《Java编程思想》</title>

<author>Bruce Eckel</author>

<price>78.00</price>

</book>

<book id="2">

<title>《深入理解Java虚拟机》</title>

<author>周志明</author>

<price>69.00</price>

</book>

<book id="3">

<title>《算法导论》</title>

<author>Thomas H.Cormen/Charles E.Leiserson/Ronald L.Rivest/Clifford Stein</author>

<price>89.00</price>

</book>

<book id="4">

<title>《高性能MySQL》</title>

<author>Baron Schwartz/Peter Zaitsev/Vadim Tkachenko</author>

<price>98.00</price>

</book>

</books>

`