2011-06-16 74 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/