包含来自另一个文件的xml以及来自父文件的内容
是否可以严格使用xml或xslt将另一个xml文件子xml的内容插入到具有更新属性的父xml中?或者我必须使用python来生成xml 例如,假设我有一个包含内容的父xml:包含来自另一个文件的xml以及来自父文件的内容,xml,xslt,dtd,Xml,Xslt,Dtd,是否可以严格使用xml或xslt将另一个xml文件子xml的内容插入到具有更新属性的父xml中?或者我必须使用python来生成xml 例如,假设我有一个包含内容的父xml: <root> <parent1 value="parent1"> # get contents of child.xml </parent1> <parent2 value="parent2">
<root>
<parent1 value="parent1">
# get contents of child.xml
</parent1>
<parent2 value="parent2">
# get contents of child.xml
</parent2>
</root>
<root>
<child1 value="child1"/>
<child2 value="child2"/>
</root>
child.xml包含以下内容:
<root>
<parent1 value="parent1">
# get contents of child.xml
</parent1>
<parent2 value="parent2">
# get contents of child.xml
</parent2>
</root>
<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>
其中子项的值根据父项值更新。您可以使用文档函数引用另一个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>
看到它在这里工作:
出于测试目的,我已将文档放入变量中。您可以使用函数加载子文档,并将其分配给样式表中的变量,然后与父内容混合:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:variable name="child-doc" select="document('child.xml')"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/root/*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates select="$child-doc/root/*" mode="child">
<xsl:with-param name="prefix" tunnel="yes" select="@value"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="@*|node()" mode="child">
<xsl:copy>
<xsl:apply-templates select="@*|node()" mode="child"/>
</xsl:copy>
</xsl:template>
<xsl:template match="root/*/@value" mode="child">
<xsl:param name="prefix" tunnel="yes"/>
<xsl:attribute name="value" select="string-join(($prefix, .), '_')"/>
</xsl:template>
</xsl:stylesheet>
谢谢你的解决方案。这对您的示例适用,但父对象并不总是父对象,它可以是parent1、parent2、something1、something2等。如何更新解决方案以使用可变父标记?您的模板需要与某个名称匹配。元素名称的第一部分是否始终相同?一种方法是使用match=parent1 | parent2 | something 1 | something 2,但如果元素名称的数量是无限的,则这将不起作用。可能会有大约20个值,但肯定比将所有子元素重复20次要好