首页 > 解决方案 > 使用 Xpath 和 XSLT 选择特定字符串

问题描述

我想在<和之间选择字符串>

输入 :

<p type="Endnote Text">&lt;p:endnote_bl1&gt;This is a bullet list in an endnote</p>
<p type="Endnote Text">&lt;p:endnote_bl2&gt;This is a bullet list in an endnote</p>
<p type="Endnote Text">&lt;p:endnote_bl3&gt;This is a bullet list in an endnote</p>

我想p:endnote_bl1,p:endnote_bl2, etc..从文本中选择。&lt;它表示和之间的任何文本&gt;。我怎样才能为此编写 XPath。

标签: xsltxpath

解决方案


在 XSLT 中,使用 xpath,您可以简单地选择所有p元素(或tps:p元素,如果您有命名空间),并使用substring-beforeandsubstring-after提取文本,但请注意,这假设每个&lt;&gt;

<xsl:for-each select="//p[@type='Endnote Text']">
  <xsl:value-of select="substring-before(substring-after(., '&lt;'), '&gt;')" />
  <xsl:text>&#10;</xsl:text>
</xsl:for-each>

在http://xsltfiddle.liberty-development.net/bnnZX7上查看它的实际应用

如果您可以使用 XSLT 2.0,则无需xsl:for-each...

<xsl:value-of select="//p[@type='Endnote Text']/substring-before(substring-after(., '&lt;'), '&gt;')" separator="&#10;" />

或者您也可以replace在 XSLT 2.0 中使用......

<xsl:value-of select="//p[@type='Endnote Text']/replace(., '&lt;(.+)&gt;.*', '$1')" separator="&#10;" />

推荐阅读