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

17 xml xpath

什么是XPath表达式,我将用于获取每本书的'HarryPotter:'之后的字符串.

即.鉴于此XML:

<bookstore>
<book>
  HarryPotter:Chamber of Secrets 
</book>
<book>
  HarryPotter:Prisoners in Azkabahn 
</book>
</bookstore>
Run Code Online (Sandbox Code Playgroud)

我会回来的:

Chamber of Secrets
Prisoners in Azkabahn 
Run Code Online (Sandbox Code Playgroud)

我尝试过这样的事情:

/bookstore/book/text()[substring-after(. , 'HarryPotter:')] 
Run Code Online (Sandbox Code Playgroud)

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

Dim*_*hev 23

在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 的密室囚犯

  • @Josh-Stodola,我在哪里说它没有substring-after()函数?XPath 1.0*不允许将*函数指定为位置步骤,如果这是substring-after()或任何其他函数.请,还原*错误*downvote! (6认同)
  • 乔希不知道迪米特是谁:) (6认同)

Ben*_*ter 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
Run Code Online (Sandbox Code Playgroud)