如何应用 XPath 函数“substring-after" [英] How to apply the XPath function 'substring-after'

查看:23
本文介绍了如何应用 XPath 函数“substring-after"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将使用什么 XPath 表达式来获取每本书的 'HarryPotter:' 后面的字符串.

即.鉴于此 XML:

<书店><书>哈利波特:密室<书>哈利波特:阿兹卡巴的囚徒</书店>

我会回来的:

密室阿兹卡巴的囚犯

我尝试过这样的事情:

/bookstore/book/text()[substring-after(. , 'HarryPotter:')]

我认为我的语法不正确...

解决方案

在 XPath 2.0 中,这可以由单个 XPath 表达式生成:

     /*/*/substring-after(., 'HarryPotter:')

这里我们使用了 XPath 2.0 非常强大的功能,在位置步骤路径的末尾,我们可以放置一个函数,该函数将应用于当前结果集中的所有节点.

在 XPath 1.0 中没有这样的功能,这不能在一个 XPath 表达式中完成.

我们可以执行如下的 XSLT 转换:

<前><xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="text"/><xsl:template match="/"><xsl:for-each select="/*/*[substring-after(., 'HarryPotter:')]"><xsl:value-of select="substring-after(., 'HarryPotter:')"/><xsl:text>&#xA;</xsl:text></xsl:for-each></xsl:模板></xsl:样式表>

应用于原始 XML 文档时:

<前><书店><book> 哈利波特:密室 </book><book> 哈利波特:阿兹卡巴的囚徒 </book>

这个转换产生了想要的结果:

密室
阿兹卡巴的囚犯

What is the XPath expression that I would use to get the string following 'HarryPotter:' for each book.

ie. Given this XML:

<bookstore>
<book>
  HarryPotter:Chamber of Secrets 
</book>
<book>
  HarryPotter:Prisoners in Azkabahn 
</book>
</bookstore>

I would get back:

Chamber of Secrets
Prisoners in Azkabahn 

I have tried something like this:

/bookstore/book/text()[substring-after(. , 'HarryPotter:')] 

I think my syntax is incorrect...

解决方案

In XPath 2.0 this can be produced by a single XPath expression:

      /*/*/substring-after(., 'HarryPotter:')

Here we are using the very powerful feature of XPath 2.0 that at the end of a path of location steps we can put a function and this function will be applied on all nodes in the current result set.

In XPath 1.0 there is no such feature and this cannot be accomplished in one XPath expression.

We could perform an XSLT transformation like the following:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

    <xsl:template match="/">
      <xsl:for-each select="/*/*[substring-after(., 'HarryPotter:')]">
        <xsl:value-of select=
         "substring-after(., 'HarryPotter:')"/>
        <xsl:text>&#xA;</xsl:text>
      </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>  

When applied on the original XML document:

<bookstore>
    <book>  HarryPotter:Chamber of Secrets </book>
    <book>  HarryPotter:Prisoners in Azkabahn </book>
</bookstore>

this transformation produces the wanted result:

Chamber of Secrets
Prisoners in Azkabahn

这篇关于如何应用 XPath 函数“substring-after"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆