2017-09-14 46 views
0

在使用我org.dom4j解析XML文檔,我使用XPath在一個節點如下:dom4j的閱讀XPath的子節點是不正確的

<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") 

     } 
    } 

結果是不對的formatNodeTranscodeParam總是第一個<Format>元素,從來沒有到第二個。

如何解決問題?

enter image description here

回答

0

在你不使用的formatNode變量,而不是你使用其他變量(node)循環:

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

此計算XPath表達式//FormatformatsNode作爲上下文節點。

以「/」開頭的任何表達式都從包含上下文節點的樹的根中選擇,而不是從上下文節點本身中選擇。如果要從上下文節點向下選擇,請使用

formatsNode.selectNodes(".//Format")