dom4j read child node by XPath is not right

963 views Asked by At

when I using org.dom4j to parse XML document, I using XPath at a node as follow:

<JobDescription>
   <Formats Description="">
    <Format Refed="format_0" Name="MOV"  >
        <TranscodeParam VideoOutputParamRef="vo_para_28"  />
        <EnhancementParam VideoEnhancementRef="ve_para_31"  />
    </Format>
    <Format Refed="format_1" Name="WMV" >
        <TranscodeParam VideoOutputParamRef="vo_para_32"  />
        <EnhancementParam VideoEnhancementRef="ve_para_35"   />
    </Format>
   </Formats>
</JobDescription>

Node formatsNode = document.selectSingleNode("//JobDescription/Formats");

    if (formatsNode != null) {

        for (Node formatNode :
                formatsNode.selectNodes("//Format")) {
             Node transcodeParaNode = node.selectSingleNode("//TranscodeParam"); //the node always get the first node(Which VideoOutputParamRef="vo_para_28")

        }
    }

The result is wrong that the formatNode's TranscodeParam is always the first one of <Format> elements, never to the second one.

How to solve the problem?

enter image description here

2

There are 2 answers

0
Michael Kay On
formatsNode.selectNodes("//Format")

This computes the XPath expression //Format with formatsNode as the context node.

Any expression starting with "/" selects from the root of the tree containing the context node, not from the context node itself. If you want to select downwards from the context node, use

formatsNode.selectNodes(".//Format")
0
Ayoub_B On

In the for loop you're not using the formatNode variable instead you're using another variable (node):

for (Node formatNode :
    formatsNode.selectNodes("//Format")) {
        Node transcodeParaNode = formatNode.selectSingleNode("//TranscodeParam"); //the node always get the first node(Which VideoOutputParamRef="vo_para_28")
}