Java中的DOM解析无法获取嵌套注释

Java中的DOM解析无法获取嵌套注释,java,xml,parsing,dom,Java,Xml,Parsing,Dom,我必须解析一个xml文件,其中有许多名称-值对。 我必须更新该值,以防它与给定的名称匹配。 我选择DOM解析,因为它可以轻松地遍历任何部分,并且可以快速更新值。 但是,当我在示例文件上运行它时,它会给我一些有线结果 我是DOM新手,如果有人能帮我解决问题。 我尝试了各种方法,但都导致内容或#文本节点名的值为空。 我无法获取标记的文本内容 DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstan

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

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

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");
        }
    }
}
DocumentBuilderFactory DocumentBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder DocumentBuilder=documentBuilderFactory.newDocumentBuilder();
Document Document=documentBuilder.parse(xmlFilePath);
//这将获得第一对NVP
节点NVPairs=document.getElementsByTagName(“NVPairs”).item(0);
//这将为节点分配NVPairs的所有子节点。这应该是理想的
//
NodeList nodes=NVPairs.getChildNodes();
对于(int i=0;i
示例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>

汤姆
12
山姆
121
#getChildNodes()
#getFirstChild()
返回所有类型的节点,而不仅仅是元素节点,在这种情况下,
Tom
的第一个子节点是文本节点(带有换行符和空格)。所以你的测试永远不会返回真值

但是,在这种情况下,使用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");
    }
XPath=XPathFactory.newInstance().newXPath();
NodeList节点=(NodeList)xpath.evaluate(
“//nameValuePair/value[前面的同级::name='Tom'],文档,
XPathConstants.NODESET);
对于(int i=0;i
即,返回所有
元素,这些元素前面有一个值为“Tom”的同级元素