请问我想知道如何使用xslt将两个xml文件合并到一个xml文件中。 我有这两个xml文件,我想合并到xml文件中,如预期的输出所示。我想将第二个文件中的每个节点 Hn 包含在相应的块中。档案1。
文件1:
<Test>
<R1>
<Th1>
here are some instruction.
</Th1>
</R1>
<R2>
<Th2>
here are some instruction.
</Th2>
</R2>
<R3>
<Th3>
here are some instruction.
</Th3>
</R3>
</Test>
文件2:
<test1>
<H1>
here are some instruction.
</H1>
<H2>
here are some instruction.
</H2>
<H3>
here are some instruction.
</H3>
</test1>
这是预期的输出:
<test2>
<R1>
<H1>
here are some instruction.
</H1>
<Th1>
here are some instruction.
</Th1>
</R1>
<R2>
<H2>
here are some instruction.
</H2>
<Th2>
here are some instruction.
</Th2>
</R2>
<R3>
<H3>
here are some instruction.
</H3>
<Th3>
here are some instruction.
</Th3>
</R3>
</test2>
感谢您的帮助。
答案 0 :(得分:2)
<强>予。这个XSLT 1.0转换:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:variable name="vDigits" select="'0123456789'"/>
<xsl:variable name="vDoc2" select="document('file:///c:/temp/delete/file2.xml')"/>
<xsl:template match="/*">
<test2><xsl:apply-templates/></test2>
</xsl:template>
<xsl:template match="/*/*">
<xsl:copy>
<xsl:text>
</xsl:text>
<xsl:copy-of select=
"$vDoc2/*/*
[translate(name(),translate(name(),$vDigits,''),'')
=
translate(name(current()),translate(name(current()),$vDigits,''),'')
]"/>
<xsl:copy-of select="node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
应用于第一个XML文档(file1.xml)时:
<Test>
<R1>
<Th1>
here are some instruction.
</Th1>
</R1>
<R2>
<Th2>
here are some instruction.
</Th2>
</R2>
<R3>
<Th3>
here are some instruction.
</Th3>
</R3>
</Test>
并将第二个XML文档驻留在c:\temp\delete\file2.xml
:
<test1>
<H1>
here are some instruction.
</H1>
<H2>
here are some instruction.
</H2>
<H3>
here are some instruction.
</H3>
</test1>
会产生想要的正确结果:
<test2>
<R1>
<H1>
here are some instruction.
</H1>
<Th1>
here are some instruction.
</Th1>
</R1>
<R2>
<H2>
here are some instruction.
</H2>
<Th2>
here are some instruction.
</Th2>
</R2>
<R3>
<H3>
here are some instruction.
</H3>
<Th3>
here are some instruction.
</Th3>
</R3>
</test2>
<强>解释强>:
正确使用Michael Kay首次演示的“双翻译”方法。
<强> II。 XSLT 2.0解决方案:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:variable name="vDigits" select="'0123456789'"/>
<xsl:variable name="vDoc2" select="document('file:///c:/temp/delete/file2.xml')"/>
<xsl:template match="/*">
<test2><xsl:apply-templates/></test2>
</xsl:template>
<xsl:template match="/*/*">
<xsl:if test="not(matches(name(), '^.+\d+$'))">
<xsl:message terminate="yes">
Element Name doesn't end with number: <xsl:sequence select="name()"/>
</xsl:message>
</xsl:if>
<xsl:copy>
<xsl:text>
</xsl:text>
<xsl:copy-of select=
"$vDoc2/*/*
[replace(name(),'^.+(\d+)$', '$1')
=
replace(name(current()),'^.+(\d+)$', '$1')
]"/>
<xsl:copy-of select="node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
<强>解释强>: