Xml 复制不同父节点下的子节点
我是XSLT新手,遇到了这个问题。Xml 复制不同父节点下的子节点,xml,xslt,Xml,Xslt,我是XSLT新手,遇到了这个问题。 输入XML <Root> <Family> <Entity> <SomeElement1/> <Child1> <Element1/> </Child1> <Child2> <Element2/> </Child2> <Entity>
输入XML
<Root>
<Family>
<Entity>
<SomeElement1/>
<Child1>
<Element1/>
</Child1>
<Child2>
<Element2/>
</Child2>
<Entity>
<SomeElement1/>
<Child1>
<Element111/>
</Child1>
<Child2>
<Element222/>
</Child2>
</Entity>
</Entity>
</Family>
</Root>
输出Xml
<Response>
<EntityRoot>
<SomeElement1/>
</EntityRoot>
<Child1Root>
<Element1>
</Child1Root>
<Child2Root>
<Element2>
</Child2Root>
<MetadataEntityRoot>
<SomeElement1/>
</MetadataEntityRoot>
<Child1Root>
<Element111>
</Child1Root>
<Child2Root>
<Element222>
</Child2Root>
</Response>
我知道如何从输入xml复制所有内容。但不确定如何排除子元素,然后在不同的根元素中再次复制它们
<!-- Copy everything -->
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
根据给出的答案尝试此操作
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Entity">
<EntityRoot>
<xsl:apply-templates select="@* | node()[not(self::Child1 | self::Child2)]" />
</EntityRoot>
<xsl:apply-templates select="Child1 | Child2" />
</xsl:template>
<xsl:template match="Child1">
<Child1Root><xsl:apply-templates select="@*|node()" /></Child1Root>
</xsl:template>
<xsl:template match="Child2">
<Child2Root><xsl:apply-templates select="@*|node()" /></Child2Root>
</xsl:template>
</xsl:stylesheet>
但得到的结果是:
<?xml version="1.0" encoding="UTF-8"?>
<Root>
<Family>
<EntityRoot>
<SomeElement1/>
</EntityRoot>
<Child1Root>
<Element1/>
</Child1Root>
<Child2Root>
<Element2/>
</Child2Root>
</Family>
</Root>
除了已有的“复制所有内容”标识模板外,您只需添加与您希望以不同方式处理的元素相匹配的特定模板。要将Child1
重命名为Child1Root
,可以使用
<xsl:template match="Child1">
<Child1Root><xsl:apply-templates select="@*|node()" /></Child1Root>
</xsl:template>
要完全剥离层(在本例中为族
),但仍包含其子层,可以使用不带副本的模板
:
<xsl:template match="Family">
<xsl:apply-templates />
</xsl:template>
它对我不起作用。根据您的答案更新我的问题。@HimanshuYadav我编辑了我的答案,以便更清楚地说明我建议的模板是您在问题中开始使用的身份模板之外的模板,而不是它。身份模板上写着“保持一切不变,除了我想更改的内容”,我建议的其他模板是“我想更改的内容”。谢谢。只是根元素。如何筛选出根元素
?请查看更新。我知道它需要一个虚假的根元素。假设是
@HimanshuYadav,我添加了更多的细节。XSLT不必复杂,您只需要熟悉基本的构建块(标识模板、删除元素的空模板、像Child1
one这样的简单重命名模板,以及像家族one那样的“忽略我,但保留我的孩子”)并以数据驱动的方式而不是程序化的方式思考您的问题。非常感谢您如此耐心。它工作得非常好。当我使用递归EntityRoot
时,只有一个条件失败。如果你愿意,我可以单独问这个问题,但我已经更新了我的问题。
<xsl:template match="Family">
<xsl:apply-templates />
</xsl:template>