如何应用XPath函数'substring-after'

时间:2008-12-02 07:15:02

标签: xml xpath

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

即。鉴于此XML:

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

我会回来的:

Chamber of Secrets
Prisoners in Azkabahn 

我尝试过这样的事情:

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

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

4 个答案:

答案 0 :(得分:22)

在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:template>
</xsl:stylesheet>  

应用于原始XML文档时:

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

这种转变产生了想要的结果:

密室 Azkabahn的囚犯

答案 1 :(得分:5)

在你的XML中,哈利波特之间没有空间,但在你的XQuery中,你有一个空间。只需将其匹配并预先设定,您就可以获得数据......

    Dim xml = <bookstore>
                  <book>HarryPotter:Chamber of Secrets</book>
                  <book>HarryPotter:Prisoners in Azkabahn</book>
                  <book>MyDummyBook:Dummy Title</book>
              </bookstore>

    Dim xdoc As New Xml.XmlDocument
    xdoc.LoadXml(xml.ToString)

    Dim Nodes = xdoc.SelectNodes("/bookstore/book/text()[substring-after(., 'HarryPotter:')]")

    Dim Iter = Nodes.GetEnumerator()
    While Iter.MoveNext
        With DirectCast(Iter.Current, Xml.XmlNode).Value
            Console.WriteLine(.Substring(.IndexOf(":") + 1))
        End With
    End While

答案 2 :(得分:4)

XPath表达式

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

将返回一个节点集,其中所有文本节点都包含值“HarryPotter:”。要使书名成功“HarryPotter:”,您需要浏览此节点集并获取每个节点的子字符串。如果您正在使用XSLT,则可以使用substring-after,如果您正在使用balabaster所示的VB,则可以使用Substring和IndexOf。

答案 3 :(得分:0)

Xpath的:

substring-after(//book, 'HarryPotter:')

我在这个领域是全新的,但对我来说,它有效......!

相关问题