2011-06-16 71 views
1

我有多個節點的XML文檔看起來是這樣的檢索子:使用XPath後的特定文本

<Result> 
     <Url>http://www.mysite.com/Topic/1/</Url> 
    </Result> 
    <Result> 
     <Url>http://www.mysite.com/Topic/2/</Url> 
    </Result> 
    <Result> 
     <Url>http://www.mysite.com/Topic/3/</Url> 
    </Result> 

我想要做的是獲取後的主題ID爲「主題/」所有節點。對於上面的示例,我正在查找值1,2和3.我可以考慮其他方法來執行此操作,但我想知道是否有方法使用XPath執行此操作?

回答

1

您可以使用子,後成對子,之前只是提取數

這是表達式

substring-before(substring-after(.,'http://www.mysite.com/Topic/'),'/') 

鑑於你輸入(我加了一個根節點,使其vaild)

<xml> 
    <Result> 
    <Url>http://www.mysite.com/Topic/1/</Url> 
    </Result> 
    <Result> 
    <Url>http://www.mysite.com/Topic/2/</Url> 
    </Result> 
    <Result> 
    <Url>http://www.mysite.com/Topic/3/</Url> 
    </Result> 
</xml> 

此轉換說明你想

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output indent="yes" method="xml"/> 
    <xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
    </xsl:template> 
    <xsl:template match="Url"> 
    <Topic> 
     <xsl:value-of select="substring-before(substring-after(.,'http://www.mysite.com/Topic/'),'/')"/> 
    </Topic> 
    </xsl:template> 
</xsl:stylesheet> 

輸出

<xml> 
    <Result> 
    <Topic>1</Topic> 
    </Result> 
    <Result> 
    <Topic>2</Topic> 
    </Result> 
    <Result> 
    <Topic>3</Topic> 
    </Result> 
</xml> 

結果根據上下文,你應將上述表達式中的.替換爲訪問節點所需的路徑。

+0

感謝您的全面回答! – Tempered 2011-06-20 14:49:08

0

使用字符串函數substring-after,就像這樣:

substring-after(string(.),'http://www.mysite.com/Topic/') 

這將返回1/