如何使用XSL使用新节点将所有内容包装到指定的XML元素中?
如何使用XSL使用新节点将所有内容包装到指定的XML元素中?,xml,xslt,xpath-1.0,Xml,Xslt,Xpath 1.0,因此,考虑到这个XML: asdf qwerty 1234lorem ipsum5678 …我怎样才能把它变成这样? asdf qwerty 1234lorem ipsum5678 然后,的每个实例将包含元素,并且每个的内容将位于新节点内。 …到目前为止,我有一个XSL,它用新节点包装每个元素,但在外部,而不是内部: …这产生了不希望的结果: asdf qwerty 1234lorem ipsum5678 在测试只需将移动到xsl:copy的内部: <xs
因此,考虑到这个XML:
asdf
qwerty
1234lorem ipsum5678
…我怎样才能把它变成这样?
asdf
qwerty
1234lorem ipsum5678
然后,
的每个实例将包含
元素,并且每个
的内容将位于新节点内。
…到目前为止,我有一个XSL,它用新节点包装每个
元素,但在外部,而不是内部:
…这产生了不希望的结果:
asdf
qwerty
1234lorem ipsum5678
在测试只需将
移动到xsl:copy
的内部:
<xsl:template match="td">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<BLAH>
<xsl:apply-templates select="node()"/>
</BLAH>
</xsl:copy>
</xsl:template>
试试这个
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes" method="xml" />
<xsl:strip-space elements="*" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="td">
<xsl:copy>
<BLAH>
<xsl:apply-templates select="@*|node()" />
</BLAH>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
我想这会将
的所有属性移动到
。谢谢@Sean的帮助。然而,正如DevNull所说的,
的任何可能属性都将通过此转换重命名为BLAH
(DevNull下面的示例--foo
将成为foo
;在进行测试)。哈哈,这比我想象的要简单得多,谢谢DevNull@安坎贝尔-不客气。请务必检查我在回答问题后立即进行的编辑,这将确保
的所有属性都保留在
中。检查--并在进行测试,以获得所需的结果。再次感谢。@IanCampbell-SeanB.Durkin在xsl:copy
中使用
意味着
中的任何属性都将移动到
。例如,foo
将变成foo
@IanCampbell-是的,尽管它没有复制属性…它正在应用属性的模板。这意味着您仍然可以使用另一个模板覆盖这些属性的处理。由于您没有与任何td
属性匹配的模板,因此您的身份模板就是进行复制的模板。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes" method="xml"/>
<xsl:strip-space elements="*"/>
<!-- identity rule -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="table//td">
<BLAH>
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</BLAH>
</xsl:template>
</xsl:stylesheet>
<root>
<table>
<tr>
<BLAH><td>asdf</td></BLAH>
<BLAH><td>qwerty</td></BLAH>
<BLAH><td>1234 <p>lorem ipsum</p> 5678</td></BLAH>
</tr>
</table>
</root>
<xsl:template match="td">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<BLAH>
<xsl:apply-templates select="node()"/>
</BLAH>
</xsl:copy>
</xsl:template>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes" method="xml" />
<xsl:strip-space elements="*" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="td">
<xsl:copy>
<BLAH>
<xsl:apply-templates select="@*|node()" />
</BLAH>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>