我有一个XML,我只想修改一个特定的部分,并保留其余部分,如何做到这一点?即我只想修改节点AA2
<root>
<parentHeader>
</parentHeader>
<body>
<ChildAA>
<AA1>
<foo>bar</foo>
<foo>bar2</foo>
</AA1>
<AA2>
<foo>bar</foo>
<foo>bar2</foo>
</AA2>
</ChildAA>
<ChildBB>
<BB1>
<foo>bar</foo>
<foo>bar2</foo>
</BB1>
<BB2>
<foo>bar</foo>
<foo>bar2</foo>
</BB2>
</ChildBB>
</body>
</root>
我有以下XSLT,它只返回修改过的部分。我怎样才能包含其他所有内容?
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- Whenever you match any node or any attribute -->
<xsl:template match="/*">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="AA2">
<RenamedAA2>
<xsl:copy-of select="."/>
</RenamedAA2>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
我正在寻找像这样的结果
<root>
<parentHeader>
</parentHeader>
<body>
<ChildAA>
<AA1>
<foo>bar</foo>
<foo>bar2</foo>
</AA1>
<RenamedAA2>
<foo>bar</foo>
</RenamedAA2>
<RenamedAA2>
<foo>bar2</foo>
</RenamedAA2>
</ChildAA>
<ChildBB>
<BB1>
<foo>bar</foo>
<foo>bar2</foo>
</BB1>
<BB2>
<foo>bar</foo>
<foo>bar2</foo>
</BB2>
</ChildBB>
</body>
</root>
答案 0 :(得分:7)
你想要的是identity transform。
您的评论Whenever you match any node or any attribute
的模板没有按照您的想法行事。它只匹配根元素。
此外,您正在使用最后一个模板剥离所有text()
个节点。
以下是您应该做的一个示例:
XSLT 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<!--Identity Transform.-->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="AA2/foo">
<RenamedAA2>
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</RenamedAA2>
</xsl:template>
<xsl:template match="AA2">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
XML输出
<root>
<parentHeader/>
<body>
<ChildAA>
<AA1>
<foo>bar</foo>
<foo>bar2</foo>
</AA1>
<RenamedAA2>
<foo>bar</foo>
</RenamedAA2>
<RenamedAA2>
<foo>bar2</foo>
</RenamedAA2>
</ChildAA>
<ChildBB>
<BB1>
<foo>bar</foo>
<foo>bar2</foo>
</BB1>
<BB2>
<foo>bar</foo>
<foo>bar2</foo>
</BB2>
</ChildBB>
</body>
</root>