![](/img/trans.png)
[英]how to transform xml with xslt preserving <br /> and not preserve other tags in a text
[英]How do I preserve all tags, structure and text in an xml document replacing only some with XSLT?
我一直在尝试将简单的xsl样式应用于xml文档:
<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的标题。 我希望能够做的是保留我的文档结构,同时只替换它的一些标签。
所以,例如,如果我有这个文件:
<section>
<title>Hello world</title>
<p>Hello!</p>
</section>
我可以得到这个:
<section>
<h1>Hello world</h1>
<p>Hello!</p>
</section>
不太确定在XSLT手册中的哪个地方开始寻找。
正如OR Mapper所说,解决方案是在转换中添加一个标识模板,然后覆盖您需要的部分。 这将是完整的解决方案:
<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>
在样本输入上运行时,会产生:
<html>
<body>
<section>
<h1>Hello world</h1>
<p>Hello!</p>
</section>
</body>
</html>
如果你真的只想保留原始XML但是替换<title>
,你可以删除中间的<xsl:template>
,你应该得到结果:
<section>
<h1>Hello world</h1>
<p>Hello!</p>
</section>
您想要只替换<title>
元素。 但是,在XSLT中,您为文档的根元素( /
)定义模板,并将整个根元素替换为模板的内容。
你真正想要做的是定义一个身份转换模板(google this,这是XSLT中的一个重要概念),基本上复制源文档中的所有内容,以及只匹配<title>
元素的模板,并用新代码替换它们, 像这样:
<xsl:template match="title">
<h1><xsl:value-of select="."/></h1>
</xsl:template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.