是否可以将另一个xml文件(子xml)的内容插入到具有更新属性的父xml中-严格使用xml或xslt?还是我必须使用python来生成xml。
例如,假设我有一个包含内容的父xml:
<root>
<parent1 value="parent1">
# get contents of child.xml
</parent1>
<parent2 value="parent2">
# get contents of child.xml
</parent2>
</root>
child.xml具有以下内容:
<root>
<child1 value="child1"/>
<child2 value="child2"/>
</root>
我可以用include来做,但是我也想更新它的值。所以我想要的最终xml是:
<root>
<parent1 value="parent1">
<child1 value="parent1_child1"/>
<child2 value="parent1_child2"/>
</parent1>
<parent2 value="parent2">
<child1 value="parent2_child1"/>
<child2 value="parent2_child2"/>
</parent2>
</root>
子项的值根据父项值进行更新。
你可以使用document()函数来引用另一个XML文件。你可以这样实现它。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml"/>
<xsl:variable name="childDoc" select="document('child.xml')"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="parent">
<xsl:variable name="currentParent" select="."/>
<xsl:copy>
<xsl:for-each select="$childDoc/root/child">
<xsl:copy>
<xsl:attribute name="value" select="concat($currentParent/@value,'_',@value)"/>
</xsl:copy>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
看到它在这里工作:https : //xsltfiddle.liberty-development.net/pNvtBGr (出于测试目的,我已将文档放在变量中。)
感谢您的解决方案。这确实适用于您的示例,但是父级并不总是父级,它可以是parent1,parent2,something1,something2等。我如何更新解决方案以使用可变的parent标记?
您的模板需要与某些名称匹配。元素名称的第一部分是否始终相同?一种方法是使用match =“ parent1 | parent2 | something1 | something2”,但如果元素名称数量不限,则该方法将无效。
也许大约是20个值,但是绝对比重复所有子元素20次更好