XPATH problem with dom4j

2019-03-07 03:42发布

问题:

I am using dom4j to overwrite a value in the XML. The XML looks like this:

<start>
    <name color="blue" time="555555">
        <element1 param="1">
            <value>value1</value>
            <value>value2</value>
            <value>value3</value>
        <element1>
    </name>

    <name color="blue" time="888888">
        <element2 param="1">
            <value>value1</value>
            <value>value2</value>
            <value>value3</value>
        <element1>
    </name>
</start>

I am trying to semect nodes by:

List list= document.selectNodes("//element1[@timetime='555555']" );

but the list returns null. I wanted to change all the 3 values where time="555555".

Isn't there a way to directly go to that node.

please help.

回答1:

to select the three values, use:

//name[@time='555555']/element1/value

If that returns null as well, there may be a default namespace involved and that means you need to show your entire XML.

XPath is flexible, if you want you can express the same like this:

//value[ancestor::name[1]/@time='555555']


回答2:

The XPath that you are using is looking for a time attribute equal to 555555 on element1. However, your time attributes are on the name nodes.

You could go either the way Tomalak suggested, or change it to:

//element1[../@time='555555']

This is looking for an element1 node with a parent who has a time attribute equal to 555555.



标签: xpath dom4j