Xml 使用XPath在特定文本后检索子字符串
我有一个包含多个节点的xml文档,看起来像这样:Xml 使用XPath在特定文本后检索子字符串,xml,xpath,Xml,Xpath,我有一个包含多个节点的xml文档,看起来像这样: <Result> <Url>http://www.mysite.com/Topic/1/</Url> </Result> <Result> <Url>http://www.mysite.com/Topic/2/</Url> </Result> <Result>
<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>
http://www.mysite.com/Topic/1/
http://www.mysite.com/Topic/2/
http://www.mysite.com/Topic/3/
我要做的是检索所有节点的“Topic/”之后的Topic ID。对于上面的示例,我正在查找值1、2和3。我可以想出其他方法,但我想知道是否有一种方法可以使用XPath来实现它?在之后使用字符串函数
子字符串,如下所示:
substring-after(string(.),'http://www.mysite.com/Topic/')
这将返回1/
您可以在与substring before配对后使用substring来提取数字
这就是表达
substring-before(substring-after(.,'http://www.mysite.com/Topic/'),'/')
根据您的输入(我添加了一个根节点以使其可用)
http://www.mysite.com/Topic/1/
http://www.mysite.com/Topic/2/
http://www.mysite.com/Topic/3/
此转换说明了所需的结果
<?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>
1.
2.
3.
根据上下文的不同,您应该将上面表达式中的
替换为访问节点所需的路径。谢谢您的全面回答!
<xml>
<Result>
<Topic>1</Topic>
</Result>
<Result>
<Topic>2</Topic>
</Result>
<Result>
<Topic>3</Topic>
</Result>
</xml>