Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

xml - How to apply the XPath function 'substring-after'

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...