如何保留 xml 文档中的所有标签、结构和文本,仅用 XSLT 替换一些? [英] How do I preserve all tags, structure and text in an xml document replacing only some with XSLT?
问题描述
我一直在尝试将简单的 xsl 样式应用于 xml 文档:
I've been trying to apply a simple xsl style to an xml document:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="//title">
<h1><xsl:value-of select="."/></h1>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
不幸的是,这似乎只是简单地忽略所有其他标签并从输出中删除它们及其内容,而我只剩下标题转换为 h1s.我希望能够做的是保留我的文档结构,同时只替换其中的一些标签.
Unfortunately, this seems to just simply ignore all other tags and remove them as well as their contents from the output, and I'm only left with titles converted to h1s. What I would like to be able to do is to have my document's structure remain, while replacing only some of its tags.
例如,如果我有这个文档:
So that for example if I have this document:
<section>
<title>Hello world</title>
<p>Hello!</p>
</section>
我可以得到这个:
<section>
<h1>Hello world</h1>
<p>Hello!</p>
</section>
不太确定从 XSLT 手册的何处开始查找.
No quite sure where in the XSLT manual to start looking.
推荐答案
正如 O. R. Mapper 所说,解决这个问题的方法是向您的转换添加一个标识模板,并只覆盖您需要的部分.这将是完整的解决方案:
As O. R. Mapper says, the solution to this is to add an identity template to your transform and just override the parts you need to. This would be the complete solution:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes" omit-xml-declaration="yes"/>
<!-- Identity template -->
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates select="@* | node()" />
</body>
</html>
</xsl:template>
<xsl:template match="title">
<h1>
<xsl:apply-templates select="@* |node()" />
</h1>
</xsl:template>
</xsl:stylesheet>
在您的示例输入上运行时,会产生:
When run on your sample input, this produces:
<html>
<body>
<section>
<h1>Hello world</h1>
<p>Hello!</p>
</section>
</body>
</html>
如果您真的只想保留原始 XML 但替换
,您可以删除中间的
并且您应该得到结果:
If you really just want to preserve your original XML but replace the <title>
, you can just remove the middle <xsl:template>
and you should get the result:
<section>
<h1>Hello world</h1>
<p>Hello!</p>
</section>
这篇关于如何保留 xml 文档中的所有标签、结构和文本,仅用 XSLT 替换一些?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!