XML合并两个文件不起作用



我知道还有其他问题与我的问题相似,但我并没有真正解决我的问题,所以我向这个很棒的社区询问我哪里出了问题。我正在尝试合并两个XML文件。

XML1

<root1>
<element1 id="x">
<subelement><element-i-want role="blubb">text</element-i-want>
<element-i-want role="bla">text</element-i-want>
</subelement>
</element1>
<element1 id="y">
<subelement><element-i-want role="blubb">text</element-i-want>
<element-i-want role="bla">text</element-i-want>
</subelement>
</element1>
</root1>

XML2

<root2>
<element2 id="y">
<subelement2>
<title>
Text
</title>
</subelement2>
</element2>
</root2>

我想要什么:

<root2>
<element2 id="y">
<subelement2>
<title>
Text
</title>
<newelement2>
<element-i-want role="blubb">text</element-i-want>
<element-i-want role="bla">text</element-i-want>
</newelement>
</subelement2>
</element2>
</root2>

元素应该是element1的granchildren,属性id="y"匹配element2 的id属性

我是如何尝试的(XSLT2.0(:

<xsl:variable name="variable" select="document($xml1)/element1"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="title">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy> 
<xsl:element name="new-element">
<xsl:copy-of select="$variable[element/@id=/element2/@id]/subelement//element-i-want"/>
</xsl:element>       
</xsl:template>

我得到的:

<root2>
<element2 id="y">
<subelement2>
<title>
Text
</title>
<newelement2/>
</subelement2>
</element2>
</root2>

有人能告诉我,我哪里错了吗?我真的不明白。非常感谢。

我总是为交叉引用定义一个密钥,但要修复路径,可以使用

<xsl:variable name="variable" select="$doc1/root1/element1"/>
<xsl:template match="title">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy> 
<xsl:element name="new-element">
<xsl:copy-of select="$variable[@id = current()/../../@id]/subelement//element-i-want"/>
</xsl:element>       
</xsl:template>

完整示例位于https://xsltfiddle.liberty-development.net/bdxtqh(当然,在您的代码中,您可以使用<xsl:param name="doc1" select="document('file1.xml')"/>而不是内联文档(。

使用关键字,使用文字结果元素和xsl:next-match,可以将代码简化为

<xsl:key name="ref" match="root1/element1" use="@id"/>
<xsl:template match="title">
<xsl:next-match/>
<new-element>
<xsl:copy-of select="key('ref', ../../@id, $doc1)/subelement/element-i-want"/>
</new-element>
</xsl:template>

完整样本位于https://xsltfiddle.liberty-development.net/bdxtqh/1.

在线示例使用XSLT3,但在使用XSLT2处理器的情况下,您可以简单地删除xsl:mode并保留您的身份转换模板。

最新更新