我是 XSLT 新手,希望将相同的属性和值添加到从第二个父节点开始的所有父节点。这里的逻辑应该是,如果存在主节点,则属性(Mainattribute)应该是一次,并且对于主节点下的所有父节点的其余部分应该具有不同的属性(childattribute),该属性在除主节点之外的所有其他节点上都应该相同。
我们有一个如下所示的输入 xml:它只有一些字段,理想情况下会有更多标签并且可能有所不同。
<?xml version="1.0" encoding="UTF-8"?>
<Header>
<Main>
<Parent2>
<status>12</status>
<statusmsg>Helo</status_text>
</Parent2>
<Parent3>
<Child1>112</Child1>
<Child2>Hai</Child2>
</Parent3>
<Parent4>
<Child3>Valley</Child3>
<Parent5>
<Child7>Kind</Child1>
<Child8>Pls</Child2>
</Parent5>
</Parent4>
</Main>
</Header>
输出应如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<Header>
<Main Mainattribute="1">
<Parent2 childattribute="1">
<status>12</status>
<statusmsg>Helo</status_text>
</Parent2>
<Parent3 childattribute="1">
<Child1>112</Child1>
<Child2>Hai</Child2>
</Parent3>
<Parent4 childattribute="1">
<Child3>Valley</Child3>
<Parent5 childattribute="1">
<Child7>Kind</Child1>
<Child8>Pls</Child2>
</Parent5>
</Parent4>
</Main>
</Header>
有人可以分享一下 XSLT 吗?我尝试了很多案例但未能实现。谢谢
下面是为第一个主节点尝试的 XSLT,但不知何故出现错误并且无法进一步继续。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<!-- Template to copy all the elements -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Main">
<Main>
<xsl:attribute name="Mainattribute">
<xsl:value-of select="1"/>
</xsl:attribute>
<xsl:apply-templates select="child::node()"/>
</Main>
</xsl:template>
</xsl:stylesheet>
增强@Aniket V的答案,您可以诉诸模式而不是依赖于标签的名称:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="Main">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="Mainattribute"><xsl:value-of select="1"/></xsl:attribute>
<xsl:apply-templates mode="parent_mode"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*" mode="parent_mode">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="childattribute"><xsl:value-of select="1"/></xsl:attribute>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Update
如果您想要更新所有具有子元素的 XML 元素(但不是顶级元素),那么您可以进行以下转换:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="Main" priority="1">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="Mainattribute"><xsl:value-of select="1"/></xsl:attribute>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[child::* and ancestor::*]">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="childattribute"><xsl:value-of select="1"/></xsl:attribute>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)