【问题标题】:DOM parsing in Java not able to get the nested notesJava中的DOM解析无法获取嵌套注释
【发布时间】:2014-11-29 05:12:53
【问题描述】:

我必须解析一个包含许多名称值对的 xml 文件。 如果它与给定名称匹配,我必须更新该值。 我选择了 DOM 解析,因为它可以轻松遍历任何部分并且可以快速更新值。 但是,当我在示例文件上运行它时,它会给我一些有线结果。

我是 DOM 新手,所以如果有人可以帮助它可以解决我的问题。 我尝试了各种方法,但都导致内容为空值或#text 节点名称。 我无法获取标签的文本内容。

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlFilePath);

//This will get the first NVPair
Node NVPairs = document.getElementsByTagName("NVPairs").item(0);


//This should assign nodes with all the child nodes of NVPairs. This should be ideally    
//<nameValuePair>
NodeList nodes = NVPairs.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {

    Node node = nodes.item(i);
    // I think it will consider both starting and closing tag as node so checking for if it has 
    //child     
    if(node.hasChildNodes())
    {
        //This should give me the content in the name tag.
        //However this is not happening
        if ("Tom".equals(node.getFirstChild().getTextContent())) {
            node.getLastChild().setTextContent("2000000");
        }
    }
}

示例 xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><application>
<NVPairs>
    <nameValuePair>
        <name>Tom</name>
        <value>12</value>
    </nameValuePair>
    <nameValuePair>
        <name>Sam</name>
        <value>121</value>
    </nameValuePair>
</NVPairs>

【问题讨论】:

    标签: java xml parsing dom


    【解决方案1】:

    #getChildNodes()#getFirstChild() 返回所有类型的节点,而不仅仅是 Element 节点,在这种情况下,&lt;name&gt;Tom&lt;/name&gt; 的第一个子节点是 Text 节点(带有换行符和空格)。所以你的测试永远不会返回 true。

    但是,在这种情况下,使用 XPath 总是更方便:

        XPath xpath = XPathFactory.newInstance().newXPath();
    
        NodeList nodes = (NodeList) xpath.evaluate(
                "//nameValuePair/value[preceding-sibling::name = 'Tom']", document,
                XPathConstants.NODESET);
    
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            node.setTextContent("2000000");
        }
    

    即,返回所有 &lt;name&gt; 元素,其前面的兄弟元素 &lt;name&gt; 的值为“Tom”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 2019-03-07
      • 1970-01-01
      相关资源
      最近更新 更多