2017-02-17 74 views
0

我有這樣的XML,獲取最遙遠的祖先節點-Xpath,XSLT

<doc> 
    <chap> 
     <sec originator="ABC"> 
      <app originator="body"> 
       <sec originator="body"> 
        <p>text</p> 
       </sec> 
      </app> 
     </sec> 
    </chap> 
    <chap> 
     <chap> 
      <app originator="DEF"> 
       <sec originator="body"> 
        <sec> 
         <p>text2</p> 
        </sec> 
       </sec> 
      </app> 
     </chap> 
    </chap> 
    <sec originator="GHI"> 
     <sec originator="body"> 
      <p>text</p> 
     </sec> 
    </sec> 
    <app originator="KLM"> 
     <sec> 
      <sec> 
       <p>text2</p> 
      </sec> 
     </sec> 
    </app> 
</doc> 

我已經模板<p>節點,從寫,我需要得到最遠距離祖先<sec><app>節點originator屬性值。

我的XPath是

//p/(ancestor::app[@originator][last()] | ancestor::sec[@originator][last()])/@originator 

這將選擇originator屬性值ABC, body, DEF, body, GHI, KLM ..但是,我需要的是ABC, DEF, GHI, KLM

我怎樣才能改變我的XPath來獲得最遠距離<sec><app>節點originator屬性值

回答

1

在可以選擇ancestor::*[self::app[@originator] | self::sec[@originator]][last()]/@originator一個p元素的情況下,看到http://xsltransform.net/bFWR5EQ

<?xml version="1.0" encoding="UTF-8" ?> 
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> 


    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="p"> 
     <p orig="{ancestor::*[self::app[@originator] | self::sec[@originator]][last()]/@originator}"> 
      <xsl:apply-templates/> 
     </p> 
    </xsl:template> 
</xsl:transform> 

<?xml version="1.0" encoding="UTF-8"?><doc> 
    <chap> 
     <sec originator="ABC"> 
      <app originator="body"> 
       <sec originator="body"> 
        <p orig="ABC">text</p> 
       </sec> 
      </app> 
     </sec> 
    </chap> 
    <chap> 
     <chap> 
      <app originator="DEF"> 
       <sec originator="body"> 
        <sec> 
         <p orig="DEF">text2</p> 
        </sec> 
       </sec> 
      </app> 
     </chap> 
    </chap> 
    <sec originator="GHI"> 
     <sec originator="body"> 
      <p orig="GHI">text</p> 
     </sec> 
    </sec> 
    <app originator="KLM"> 
     <sec> 
      <sec> 
       <p orig="KLM">text2</p> 
      </sec> 
     </sec> 
    </app> 
</doc>