【发布时间】:2015-10-07 02:03:27
【问题描述】:
我有一个 XML 文档,其中包含一个包含 xhtml 的“body”元素。我正在尝试处理该 html 以删除一些非标准标签。源 xml 文档中没有使用命名空间。
XML 如下所示:
<article>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3 <fig></fig></p>
</body>
</article>
XSLT 如下所示:
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="p">
<![CDATA[<div>HIT A P</div>]]>
<xsl:apply-templates mode="copy" select="@*|node()"/>
</xsl:template>
</xsl:stylesheet>
输出是这样的——我不明白为什么它只找到第一个 p 标签:
<div>HIT A P</div>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3 <fig></fig></p>
知道为什么 p 模板只在第一次触发而不是所有 3 段都触发吗??
我也在试图弄清楚为什么添加它不会导致“fig”元素被删除:
<xsl:template match="fig" />
感谢您抽出宝贵时间帮助我。
更新:非常感谢您的回复。我试图过分简化这个问题。我真正在做的是两个 XSLT 进程 - 一个将数据组织成标准格式,第二个 XSLT 进程查看正文中的 HTML 并复制除某些非标准标签之外的所有内容。
我认为我遇到的问题是,在第一个 XSLT 进程之后,正文中的 HTML 是 htmlencoded,而且似乎第二个 XSLT 进程无法转换 HTML。这里有一个更好的例子来说明实际发生的事情:
这是新的 XML(它是早期 xslt 转换的结果 - 因此文本被编码):
<document>
<article>
<title>SAMPLE TITLE</title>
<bodytext>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>
Paragraph 4 - contains non-standard fig tag
<fig>
<graphic href="testgraphic.jpg"/>
</fig>
</p>
</bodytext>
</article>
</document>
这是新的 XSLT:
<xsl:output method="html" encoding="utf-8" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="p">
<![CDATA[<div>HIT A P</div>]]>
<xsl:apply-templates mode="copy" select="@*|node()"/>
</xsl:template>
<xsl:template match="bodytext">
<![CDATA[<div>HELLO FROM BODYTEXT</div>]]>
<xsl:element name="bodytext">
<xsl:apply-templates />
</xsl:element>
</xsl:template>
<!-- THIS APPEARS TO NEVER GET HIT -->
<xsl:template match="fig" />
</xsl:stylesheet>
当我运行它时,我得到以下信息:
<document>
<article>
<title>SAMPLE TITLE</title>
<div>HELLO FROM BODYTEXT</div><bodytext>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>
Paragraph 4 - contains non-standard fig tag
<fig>
<graphic href="testgraphic.jpg"/>
</fig>
</p>
</bodytext>
</article>
</document>
在此示例中,它无法处理每个段落并删除无花果。但是,如果 XML 不是 htmlencoded,它可以工作。这是工作的 XML:
<document>
<article>
<title>SAMPLE TITLE</title>
<bodytext>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3 <fig></fig></p>
</bodytext>
</article>
</document>
这是输出:
<document>
<article>
<title>SAMPLE TITLE</title>
<div>HELLO FROM BODYTEXT</div><bodytext>
<div>HIT A P</div>Paragraph 1
<div>HIT A P</div>Paragraph 2
<div>HIT A P</div>Paragraph 3
</bodytext>
</article>
</document>
你知道当传入的数据是 htmlencoded 时我可以如何执行第二个过程吗?再次感谢。
【问题讨论】:
-
这里没有什么奇怪的。您显示的不是 htmlencoded,而是转义的 XML。转义的 XML 不是 XML - 请参阅:stackoverflow.com/questions/27018244/…