示例 xml 是:
<a amp="a"><b><c>this is the text</c></b></a>
需要转换为:
<a amp="a"><c>this is the text</c></a>
最佳答案
解决方案#1:对 smaccoun 解决方案的轻微改进,将保留 c
上的所有属性。元素(对于 XML 来说不是必需的):
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="c">
<xsl:copy-of select="." />
</xsl:template>
</xsl:stylesheet>
解决方案 #2 另一种利用 built-in template rules 的替代方案,为所有元素应用模板并复制所有 text()
:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!--identity template for the c element, it's decendant nodes,
and attributes (which will only get applied from c or
descendant elements)-->
<xsl:template match="@*|c//node()|c">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
解决方案#3:修改后的 identity transform:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!--identity template, copies all content by default-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!--don't generate content for these matched elements,
just apply-templates to it's children-->
<xsl:template match="a|b">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
解决方案#4如果您知道自己想要什么,只需从根节点上的匹配中复制它即可
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<xsl:copy-of select="a/b/c" />
</xsl:template>
</xsl:stylesheet>
如果您想简单地删除 <b>
元素,那么修改后的身份转换应与匹配 <b>
的模板一起使用简单地将模板应用于其子元素的元素。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!--identity template, copies all content by default-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!--don't generate content for the <b>, just apply-templates to it's children-->
<xsl:template match="b">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
关于xml - 如何使用 xslt 删除最外层的包装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13616348/