java - 使用 nodeList 创建 XML 文档

标签 java xml dom backend nodelist

我需要使用 NodeList 创建一个 XML 文档对象。有人可以帮我做这个吗?这是我的 Java 代码:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*; 
import org.w3c.dom.*;

public class ReadFile {

    public static void main(String[] args) {
        String exp = "/configs/markets";
        String path = "testConfig.xml";
        try {
            Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);
            XPath xPath = XPathFactory.newInstance().newXPath();
            XPathExpression xPathExpression = xPath.compile(exp);
            NodeList nodes = (NodeList)
              xPathExpression.evaluate(xmlDocument,
                                       XPathConstants.NODESET);

        } catch (Exception ex) {
            ex.printStackTrace();
        } 
    }
}

我想要一个这样的 XML 文件:

<configs>
    <markets>   
        <market>
            <name>Real</name>
        </market>
        <market>
            <name>play</name>
        </market>
    </markets>
</configs>

提前致谢。

最佳答案

你应该这样做:

  • 您创建一个新的 org.w3c.dom.Document newXmlDoc,您将节点存储在 NodeList 中,
  • 您创建一个新的根元素,并将其附加到 newXmlDoc
  • 然后,对于 NodeList 中的每个节点 n,在 newXmlDoc 中导入 n,然后您将 n 附加为 root
  • 的子级

代码如下:

public static void main(String[] args) {
    String exp = "/configs/markets/market";
    String path = "src/a/testConfig.xml";
    try {
        Document xmlDocument = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().parse(path);

        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression xPathExpression = xPath.compile(exp);
        NodeList nodes = (NodeList) xPathExpression.
                evaluate(xmlDocument, XPathConstants.NODESET);

        Document newXmlDocument = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().newDocument();
        Element root = newXmlDocument.createElement("root");
        newXmlDocument.appendChild(root);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            Node copyNode = newXmlDocument.importNode(node, true);
            root.appendChild(copyNode);
        }

        printTree(newXmlDocument);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public static void printXmlDocument(Document document) {
    DOMImplementationLS domImplementationLS = 
        (DOMImplementationLS) document.getImplementation();
    LSSerializer lsSerializer = 
        domImplementationLS.createLSSerializer();
    String string = lsSerializer.writeToString(document);
    System.out.println(string);
}

输出是:

<?xml version="1.0" encoding="UTF-16"?>
<root><market>
            <name>Real</name>
        </market><market>
            <name>play</name>
        </market></root>

一些注意事项:

  • 我已将 exp 更改为 /configs/markets/market,因为我怀疑您想要复制 market 元素,而不是单个 markets 元素
  • 对于 printXmlDocument,我在 answer 中使用了有趣的代码

希望对您有所帮助。


如果您不想创建新的根元素,那么您可以使用原始的 XPath 表达式,它返回一个由单个节点组成的 NodeList(请记住,您的 XML 必须具有单个根元素),您可以直接将其添加到新的 XML 文档中。

请参阅以下代码,其中我对上面代码中的行进行了注释:

public static void main(String[] args) {
    //String exp = "/configs/markets/market/";
    String exp = "/configs/markets";
    String path = "src/a/testConfig.xml";
    try {
        Document xmlDocument = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().parse(path);

        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression xPathExpression = xPath.compile(exp);
        NodeList nodes = (NodeList) xPathExpression.
        evaluate(xmlDocument,XPathConstants.NODESET);

        Document newXmlDocument = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().newDocument();
        //Element root = newXmlDocument.createElement("root");
        //newXmlDocument.appendChild(root);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            Node copyNode = newXmlDocument.importNode(node, true);
            newXmlDocument.appendChild(copyNode);
            //root.appendChild(copyNode);
        }

        printXmlDocument(newXmlDocument);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

这将为您提供以下输出:

<?xml version="1.0" encoding="UTF-16"?>
<markets>   
        <market>
            <name>Real</name>
        </market>
        <market>
            <name>play</name>
        </market>
    </markets>

关于java - 使用 nodeList 创建 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5786936/

相关文章:

java - 在我的代码中 BufferedReader 的 mark(0) 和 reset() 不起作用

java - 隐马尔可夫模型阈值化

javascript - 将 XML 文件中的数据添加到 JS 对象数组中

xml - 如何在Scala XML中使用not操作进行选择?

Java Spring MVC & Jackson : get only selected variables from entities

java play 框架覆盖注释失败,java.source=1.6

python - 向 hr.employees 添加字段

php - 在php中解析HTML表格

javascript - 在不使用 insertNode 的情况下在插入符处粘贴 HTML

javascript - 在运行时将 Google Chart 容器更改为另一个容器