2011-05-16 80 views
2

我想有xpath,即獲取沒有祖先的節點,它是特定節點的第一個後裔。獲取沒有特定祖先的節點xml xpath

假設我們有XML文檔這樣的:

<a> 
    <b>This node</b> 
    <c> 
    <a> 
     <b>not this</b> 
     <g> 
     <b>not this</b> 
     </g> 
    </a> 
    <a> 
     <b>This node</b> 
     <c/> 
    </a> 
    </c> 
</a> 


<a> 
    <c> 
    <a> 
     <b>not this</b> 
    </a> 
    <a> 
     <b>This node</b> 
    </a> 
    <a> 
     <b>This node</b> 
    </a> 
    <a> 
     <b>This node</b> 
    </a> 
    </c> 
</a> 


<d> 
    <b>This node</b> 
</d> 

我想選擇不作爲其祖先節點在文檔中的所有節點b // A/C/A [1]。

+0

此* *不是格式良好的XML文檔。它嚴重畸形!!! – 2011-05-16 02:42:47

+0

我非常抱歉,現在應該沒問題。 – tach 2011-05-16 02:51:19

+0

它仍然不是良構 - 格式良好的XML文檔只有一個頂層元素。你在問題中的那個人有三個頂級元素。 – 2011-05-16 03:00:18

回答

6

我想選擇不作爲其 祖先節點//a/c/a[1]

使用此XPath表達式在 文檔中的所有節點b:

//b[not(ancestor::a 
      [parent::c[parent::a] 
      and 
       not(preceding-sibling::a) 
      ] 
     ) 
    ] 

這將選擇所有b文檔中沒有祖先的元素a有一個父項c已有父母aa有父母c的祖先不是其父母的第一個a孩子。

鑑於下面的XML文檔(基於所提供的,但製成良好且也把在節點標識文本應當被選):

<t> 
    <a> 
     <b>This node 1</b> 
     <c> 
      <a> 
       <b>not this</b> 
       <g> 
        <b>not this</b> 
       </g> 
      </a> 
      <a> 
       <b>This node 2</b> 
       <c/> 
      </a> 
     </c> 
    </a> 
    <a> 
     <c> 
      <a> 
       <b>not this</b> 
      </a> 
      <a> 
       <b>This node 3</b> 
      </a> 
      <a> 
       <b>This node 4</b> 
      </a> 
      <a> 
       <b>This node 5</b> 
      </a> 
     </c> 
    </a> 
    <d> 
     <b>This node 6</b> 
    </d> 
</t> 

完全想6個b元件被選中。

驗證使用XSLT

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

<xsl:template match="/"> 
<xsl:copy-of select= 
"//b[not(ancestor::a 
      [parent::c[parent::a] 
      and 
       not(preceding-sibling::a) 
      ] 
     ) 
    ] 

"/> 
</xsl:template> 
</xsl:stylesheet> 

當該變換被應用上述的XML文檔,完全想b元件被選擇和複製到輸出。生成想要的,正確的結果

<b>This node 1</b> 
<b>This node 2</b> 
<b>This node 3</b> 
<b>This node 4</b> 
<b>This node 5</b> 
<b>This node 6</b> 
+0

哇,非常感謝,你救了我的命! – tach 2011-05-16 03:03:10

+0

@tach:不客氣。 – 2011-05-16 03:13:35

相關問題