2011-12-09 54 views
1

我有一個網站結構的XML文件,並希望基於該節點及其父母的連接值搜索節點。連接祖先價值的Xpath搜索

這裏是XML的一個樣本:

<site> 
    <page id="1"> 
     <url></url> 
     <url>home</url> 
     <page id="2"> 
      <url>about-us</url> 
     </page> 
     <page id="3"> 
      <url>locations</url> 
      <page id="4"> 
       <url>scotland</url> 
       <page id="5"> 
        <url>glasgow</url> 
       </page> 
       <page id="6"> 
        <url>edinburgh</url> 
       </page> 
      </page> 
     </page> 
    </page> 
</site> 

因此,如果URL是/locations/scotland/edinburgh我願意選擇id=6頁。

我希望XPath查詢可能是東西的境界......

//page[fn:string-join(ancestor-or-self::page[ 
       url='locations/scotland/edinburgh'],'/')] 

任何提示將真棒。

回答

1

請先的URL分成其路徑成分(其可以使用XPath 2.0很容易做到,但不是在所有的XPath 1.0),然後構造並評估該XPath表達式

//page[url='locations'] 
     /page[url='scotland'] 
      /page[url='edinburgh'] 
      /@id 

這會選擇所需的id屬性。

id屬性(6)的字符串值是評價以下XPath表達式的結果:

string(//page[url='locations'] 
      /page[url='scotland'] 
      /page[url='edinburgh'] 
       /@id 
     ) 

更新

單一的通用的XPath 2.0表達式存在給定包含Url的名爲$pUrl的參數,找到具有所需屬性的所有page元素:

//page 
    [ends-with(
       concat('/', 
        string-join(ancestor-or-self::*/url, '/') 
        ), 
       $pUrl 
      ) 
    ] 

XSLT 2.0驗證

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

<xsl:param name="pUrl" select="'/locations/scotland/edinburgh'"/> 

<xsl:template match="/"> 

    <xsl:sequence select= 
    "//page 
     [ends-with(
        concat('/', 
         string-join(ancestor-or-self::*/url, '/') 
         ), 
        $pUrl 
       ) 
     ] 
    "/> 
</xsl:template> 
</xsl:stylesheet> 

**when this transformation is applied on the provided XML document**: 

<site> 
    <page id="1"> 
     <url></url> 
     <url>home</url> 
     <page id="2"> 
      <url>about-us</url> 
     </page> 
     <page id="3"> 
      <url>locations</url> 
      <page id="4"> 
       <url>scotland</url> 
       <page id="5"> 
        <url>glasgow</url> 
       </page> 
       <page id="6"> 
        <url>edinburgh</url> 
       </page> 
      </page> 
     </page> 
    </page> 
</site> 

想要的,正確的page元素被選中並輸出

<page id="6"> 
    <url>edinburgh</url> 
</page> 
+0

是有沒有辦法URL字符串比較爲一個連接字符串每個url節點和它們的祖先?我寧願不必每次都建立一個新的查詢... –

+0

@IWood:不,除非你先連接所有的'url'屬性 - 這可以在單個XPAth 2.0表達式中完成,但不能僅用一個XPath 1.0表達式表示。 –

+0

確定如此連接url部分 - xpath2查詢會類似於什麼? –