我想复制xml的一个节点并将其粘贴到同一级别。
假设我有一个xml,如下所示。
<MyXml>
<system>
<Groups>
<Group id="01" check="true">
<name>Value</name>
<age>test</age>
</Group>
<Group id="02" check="true">
<name>Value</name>
<age>test</age>
</Group>
<Group id="03" check="true">
<name>Value</name>
<age>test</age>
</Group>
</Groups>
</system>
</MyXml>
我想复制组03并使用XSL转换粘贴到与"04"相同的级别(组内(。
预期输出
<MyXml>
<system>
<Groups>
<Group id="01" check="true">
<name>Value</name>
<age>test</age>
</Group>
<Group id="02" check="true">
<name>Value</name>
<age>test</age>
</Group>
<Group id="03" check="true">
<name>Value</name>
<age>test</age>
</Group>
<Group id="04" check="true">
<name>Value</name>
<age>test</age>
</Group>
</Groups>
</system>
</MyXml>
有人能帮我完成XSL样式表吗。不确定下面的xsl是否正确。提前谢谢。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:param name="groupId" />
<xsl:param name="newGroupId" />
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="MyXML/system/Groups/Group[@id=$groupId]" >
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<!--Wanted to do something for pasting the copied node and changing the id value with new Group Id.-->
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
在XSLT1.0中,在模板匹配中使用变量表达式实际上被认为是一个错误(尽管您可能会发现一些处理器允许这样做(。
但您可能应该做的是,在模板中调用与Group
匹配的身份模板,然后用xsl:if
来决定是否复制它
试试这个模板而不是
<xsl:template match="Group" >
<xsl:call-template name="identity" />;
<xsl:if test="@id = $groupId">
<group id="{$newGroupId}">
<xsl:apply-templates select="@*[name() != 'id']|node()"/>
</group>
</xsl:if>
</xsl:template>
请注意,在模板匹配中不需要Group
的完整路径,除非在其他级别中存在您不想匹配的Group
元素。(此外,当前匹配引用的是MyXML
,而XML将其作为MyXml
。XSLT区分大小写,因此不匹配(。