xml - 使用 XSLT 从带有嵌入链接的 XML 中提取纯文本

标签 xml xslt xpath

我正在尝试从 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/

相关文章:

java - 使用java向远程服务发送xml请求

xml - XSLT 1.0 值查找映射

java - 在 XML DTD 的枚举属性值中插入特殊字符,如 "#"

php - 使用 php 将 .xml 的一部分导入到 sql 数据库

arrays - XML 到 powershell 数组

XSLT:如何仅根据值为节点生成唯一 ID

xslt - 如何从xml文件中删除根元素

css - 经常更改的表中单元格的 Ruby/Selenium 访问属性

python - 检查文本中是否存在大量关键字

javascript - xpath 在 javascript 中使用命名空间进行评估的问题