我正在尝试从 XML 中提取类似于以下内容的文本:
<p>This is a paragraph <a href='http://link.com'>with an embedded link</a> with more text afterwards</p>
我希望提取的文本保留段落中的 URL,如下所示:
This is a paragraph with an embedded link (http://link.com) with more text afterwards
提取文本相当简单:
<xsl:value-of select="p"/>
和网址:<xsl:value-of select="p/a/@href"/>
,但我正在努力想办法使用 XSLT 将 URL 嵌入到提取的文本中。
关于如何做到这一点有什么想法吗?
如果没有简单的方法来做到这一点,我可能最终要么对文本进行一些预处理以嵌入 URL,然后使用 XSLT 从那里提取所有文本。
最佳答案
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="a">
<xsl:value-of select="."/>
<xsl:value-of select="concat(' (', @href, ')')"/>
</xsl:template>
</xsl:stylesheet>
模板<xsl:template match="text()">
匹配文本节点并简单地输出它们。
模板<xsl:template match="a">
输出 a
的内容元素及其(@href)
值。
关于xml - 使用 XSLT 从带有嵌入链接的 XML 中提取纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7990244/