xPath Java - 更改项关闭的值

时间:2016-04-22 08:00:59

标签: java xml xpath

我是xPath的初学者,而我的XML我的项目很接近(空)

<Info>  
    <Personne>
         <field name="Name" type="String">
             <value type="String"> TOTO </value>
        </field>>
        <field name="CountryCode" type="String">
             <empty />
        </field>
    </Personne>
    <Personne>
        <field name="Name" type="String">
             <value type="String"> TOTO </value>
        </field>>
        <field name="CountryCode" type="String">
            <empty />
        </field>
    </Personne> 

ETC.......

</Info>

我似乎无法阅读空白物品

expression = "/Personne/field[@name='Name']/* | 
                  /Personne/field[@name='CountryCode']/*";    

NodeList nodes = (NodeList) xPath.compile(expression)
                      .evaluate(document, XPathConstants.NODESET);    

for (int i = 0; i < nodes.getLength(); i++){
    System.out.print(nodes.item(i).getFirstChild().getNodeValue());
}   

我在表格中找到了姓名的值

我会给#34;空&#34;一个值String,例如&#34; null&#34;在我的节点表

  • 我的XML文件非常大! (1M行...)和大约750 000空

  • JDom花了很多时间......

谢谢!

3 个答案:

答案 0 :(得分:1)

选择了节点,但getNodeValue()为空元素返回""

由于您使用了System.out.print,因此您看不到空元素的任何输出。

只需检查值是否为空,然后将其转换为null

String value = nodes.item(i).getFirstChild().getNodeValue();
if ("".equals(value))
     value = null;
System.out.print(value);

答案 1 :(得分:0)

您的XML示例包含“Personne”节点,但您的XPath表达式包含“Personnes”...是拼写错误吗?打印节点名称及其值可能值得您花些时间:

是System.out.print(nodes.item(ⅰ).getFirstChild()getNodeName()+ “:”。+ nodes.item(ⅰ).getFirstChild()getNodeValue());

答案 2 :(得分:0)

如果元素可以为空,我不会尝试访问子节点,而是用例如读出文本内容。

expression = "/Personne/field[@name='Name']/* | 
                  /Personne/field[@name='CountryCode']/*";    

NodeList nodes = (NodeList) xPath.compile(expression)
                      .evaluate(document, XPathConstants.NODESET);    

for (int i = 0; i < nodes.getLength(); i++){
    String value = nodes.item(i).getTextContent();
    System.out.print(value.equals("") ? "null" : value);
}