简体   繁体   中英

Java xPath expression - Change the value of a node not found

Today I tried to know a value in a node but sometimes I have a closed node ... For example XML:

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

To read my XML file (in my java code) I use:

expression = "/Personnes/field[@name='Name']/value | /Personnes/field[@name='CountryCode']/value ";

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()
    }

But I want when xPath 'll read the <empty /> it shows me by example "EMPTY" and not anything ..

Thanks a lot !

Assuming that field can only have either value or empty child element, then you can try to modify the XPath from /value to /* . This way the XPath will still return something in case of no value element found

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM