我已经寻找了一段时间,并尝试了很多选择,这些选择部分地满足了我的要求。我对XSLT不够熟悉,无法将它们组合成我想要的东西。感谢您的帮助。
我的xml
<?xml version="1.0" encoding="UTF-8"?>
<parent>
<id>1</id>
<child>
<a>sample</a>
</child>
</parent>
<parent>
<id>2</id>
<child>
<a>sample</a>
</child>
</parent>
输出必须如下:
<parent>
<id>1</id>
<child>
<id>1</d>
<a>sample</a>
</child>
</parent>
<parent>
<id>2</id>
<child>
<id>2</id>
<a>sample</a>
</child>
</parent>
我发现一个xsl代码可以执行我想要的操作,但是它复制属性,而我需要复制ID内的数字(没有将ID设置为属性的选项)。我还想知道xls是否有可能知道哪个父级/ id必须附加到哪个孩子,因为它们都是相同的。
我相信您的输入XML缺少根元素,因此我使用了以下输入XML:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<parent>
<id>1</id>
<child>
<a>sample</a>
</child>
</parent>
<parent>
<id>2</id>
<child>
<a>sample</a>
</child>
</parent>
</data>
如果我应用此XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<!-- Identity to copy all elements -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<!-- Match on element child and copy this element, but on top add a new element
<id> and fill this with the ancestor element called parent and it's child id -->
<xsl:template match="child">
<xsl:copy>
<xsl:apply-templates select="@*" /> <!-- Copy attributes first because we will add a node after this -->
<id><xsl:value-of select="ancestor::parent/id" /></id>
<xsl:apply-templates select="node()" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
输出将是:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<parent>
<id>1</id>
<child>
<id>1</id>
<a>sample</a>
</child>
</parent>
<parent>
<id>2</id>
<child>
<id>2</id>
<a>sample</a>
</child>
</parent>
</data>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句