首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用XPath检索特定文本后的子字符串

使用XPath检索特定文本后的子字符串
EN

Stack Overflow用户
提问于 2011-06-17 00:34:48
回答 2查看 4.6K关注 0票数 2

我有一个包含多个节点的xml文档,如下所示:

代码语言:javascript
运行
复制
    <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>

我想要做的是检索所有节点的" Topic /“之后的主题ID。对于上面的示例,我正在寻找值1、2和3。我可以想到其他方法,但我想知道是否有使用XPath的方法?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-06-17 10:07:07

您可以使用substring-after和substring-before来仅提取数字

这是表达式

代码语言:javascript
运行
复制
substring-before(substring-after(.,'http://www.mysite.com/Topic/'),'/')

给定您的输入(我添加了一个根节点以使其有效)

代码语言:javascript
运行
复制
<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>

此转换说明了您想要的结果

代码语言:javascript
运行
复制
<?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>

输出

代码语言:javascript
运行
复制
<xml>
  <Result>
    <Topic>1</Topic>
  </Result>
  <Result>
    <Topic>2</Topic>
  </Result>
  <Result>
    <Topic>3</Topic>
  </Result>
</xml>

根据上下文,您应该将上面表达式中的.替换为访问节点所需的路径。

票数 3
EN

Stack Overflow用户

发布于 2011-06-17 00:54:37

使用字符串函数substring-after,如下所示:

代码语言:javascript
运行
复制
substring-after(string(.),'http://www.mysite.com/Topic/')

这将返回1/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6375391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档