专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 在Java中修改XML文件

在Java中修改XML文件

更新时间:2021-12-06 09:16:00 来源:动力节点 浏览2727次

1.XML文件,前后

原始 XML 文件。

<?xml version="1.0" encoding="utf-8"?>
<company>
    <staff id="1001">
        <name>mkyong</name>
        <role>support</role>
    </staff>
    <staff id="1002">
        <name>yflow</name>
        <role>admin</role>
    </staff>
</company>

稍后我们将使用 DOM 解析器来修改以下 XML 数据。

对于员工 ID 1001

删除 XML 元素name。

对于 XML 元素role,将值更新为“创始人”。

对于员工 ID 1002

将 XML 属性更新为2222.

添加一个新的 XML 元素salary,包含属性和值。

添加新的 XML 注释。

重命名 XML 元素,从name到n(删除和添加)。

下面是最终修改的 XML 文件。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
    <staff id="1001">
        <role>founder</role>
    </staff>
    <staff id="2222">
        <role>admin</role>
        <salary currency="USD">1000</salary>
        <!--from name to n-->
        <n>yflow</n>
    </staff>
</company>

2.Dom Parser修改XML文件

下面是 DOM 解析器示例,以获取原始 XML 文件staff-simple.xml,修改 XML 并生成修改后的 XML 文件staff-modified.xml。

package com.mkyong.xml.dom;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
public class ModifyXmlDomParser {
    private static final String FILENAME = "src/main/resources/staff-simple.xml";
    // xslt for pretty print only, no special task
    private static final String FORMAT_XSLT = "src/main/resources/xslt/staff-format.xslt";
    public static void main(String[] args) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try (InputStream is = new FileInputStream(FILENAME)) {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(is);
            NodeList listOfStaff = doc.getElementsByTagName("staff");
            //System.out.println(listOfStaff.getLength()); // 2
            for (int i = 0; i < listOfStaff.getLength(); i++) {
                // get first staff
                Node staff = listOfStaff.item(i);
                if (staff.getNodeType() == Node.ELEMENT_NODE) {
                    String id = staff.getAttributes().getNamedItem("id").getTextContent();
                    if ("1001".equals(id.trim())) {
                        NodeList childNodes = staff.getChildNodes();
                        for (int j = 0; j < childNodes.getLength(); j++) {
                            Node item = childNodes.item(j);
                            if (item.getNodeType() == Node.ELEMENT_NODE) {
                                if ("role".equalsIgnoreCase(item.getNodeName())) {
                                    // update xml element `role` text
                                    item.setTextContent("founder");
                                }
                                if ("name".equalsIgnoreCase(item.getNodeName())) {
                                    // remove xml element `name`
                                    staff.removeChild(item);
                                }
                            }
                        }
                        // add a new xml element, address
                        Element address = doc.createElement("address");
                        // add a new xml CDATA
                        CDATASection cdataSection =
                                doc.createCDATASection("HTML tag <code>testing</code>");
                        address.appendChild(cdataSection);
                        staff.appendChild(address);
                    }
                    if ("1002".equals(id.trim())) {
                        // update xml attribute, from 1002 to 2222
                        staff.getAttributes().getNamedItem("id").setTextContent("2222");
                        // add a new xml element, salary
                        Element salary = doc.createElement("salary");
                        salary.setAttribute("currency", "USD");
                        salary.appendChild(doc.createTextNode("1000"));
                        staff.appendChild(salary);
                        // rename a xml element from `name` to `n`
                        // sorry, no API for this, we need to remove and create
                        NodeList childNodes = staff.getChildNodes();
                        for (int j = 0; j < childNodes.getLength(); j++) {
                            Node item = childNodes.item(j);
                            if (item.getNodeType() == Node.ELEMENT_NODE) {
                                if ("name".equalsIgnoreCase(item.getNodeName())) {
                                    // Get the text of element `name`
                                    String name = item.getTextContent();
                                    // remove xml element `name`
                                    staff.removeChild(item);
                                    // add a new xml element, n
                                    Element n = doc.createElement("n");
                                    n.appendChild(doc.createTextNode(name));
                                    // add a new comment
                                    Comment comment = doc.createComment("from name to n");
                                    staff.appendChild(comment);
                                    staff.appendChild(n);
                                }
                            }
                        }
                    }
                }
            }
            // output to console
            // writeXml(doc, System.out);
            try (FileOutputStream output =
                         new FileOutputStream("c:\\test\\staff-modified.xml")) {
                writeXml(doc, output);
            }
        } catch (ParserConfigurationException | SAXException
                | IOException | TransformerException e) {
            e.printStackTrace();
        }
    }
    // write doc to output stream
    private static void writeXml(Document doc,
                                 OutputStream output)
            throws TransformerException, UnsupportedEncodingException {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        // The default add many empty new line, not sure why?
        // https://mkyong.com/java/pretty-print-xml-with-java-dom-and-xslt/
        // Transformer transformer = transformerFactory.newTransformer();
        // add a xslt to remove the extra newlines
        Transformer transformer = transformerFactory.newTransformer(
                new StreamSource(new File(FORMAT_XSLT)));
        // pretty print
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(output);
        transformer.transform(source, result);
    }
}

输出 – 修改后的 XML 文件。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
    <staff id="1001">
        <role>founder</role>
        <address>
            <![CDATA[HTML tag <code>testing</code>]]>
        </address>
    </staff>
    <staff id="2222">
        <role>admin</role>
        <salary currency="USD">1000</salary>
        <!--from name to n-->
        <n>yflow</n>
    </staff>
</company>

3. 下载源代码

$ git clone https://github.com/mkyong/core-java
$ cd java-xml
$ cd src/main/java/com/mkyong/xml/dom/

通过上述介绍相信大家对在Java中修改XML文件的方法已经有所了解,大家如果想了解更多相关知识,可以关注一下动力节点的Java视频,里面的课程内容详细,由浅到深,通俗易懂,适合小白观看学习,希望对大家能够有所帮助。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>