繁体   English   中英

如何使用XSLT通过id属性合并两个不同的节点组

[英]How to merge two different node groups by the id attribute using XSLT

我具有以下XML结构:

<file>
  <root1>
          <object1 id="abc" info="blah"/>
          <object1 id="def" info="blah blah"/>
  </root1>


  <root2>
          <object2 id="abc" x="10" y="20"/>
          <object2 id="def" x="30" y="40""/>
  </root2>
</file>

我想将其转换(合并)为以下结构:

<file>
  <root>
          <object id="abc" info="blah" x="10" y="20"/>
          <object id="def" info="blah blah" x="30" y="40"/>
  </root>
</file>

我们可以假设没有相同ID的重复节点或属性。

当前,我正在使用<xsl:for-each ...>遍历object1整个集合,但是我不知道如何实现此目的:

<xsl:for-each select="file/root1/object1">
  <object>
    <xsl:attribute name="id"><xsl:value-of select="@id"/></xsl:attribute>
    <xsl:attribute name="info"><xsl:value-of select="@info"/></xsl:attribute>
    <xsl:attribute name="x">???</xsl:attribute>
    <xsl:attribute name="y">???</xsl:attribute>
  </object>
</xsl:for-each>

即我需要使用当前选择的<object1>@id作为<object2>上xpath查询的输入,该<object>位于<object>的属性内。

我见过这个这个这个这个这个这个 ,但他们都有点不同,我不能看我如何使用它在我的情况。

以下样式表:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:key name="object2" match="object2" use="@id" />

<xsl:template match="/">
    <file>
        <root>
            <xsl:for-each select="file/root1/object1">
                <object>
                    <xsl:copy-of select="@* | key('object2', @id)/@*"/>
                </object>
            </xsl:for-each>
        </root> 
    </file>
</xsl:template>

</xsl:stylesheet>

当应用于您的输入示例(针对格式正确的校正)时,将产生:

<?xml version="1.0" encoding="UTF-8"?>
<file>
   <root>
      <object id="abc" info="blah" x="10" y="20"/>
      <object id="def" info="blah blah" x="30" y="40"/>
   </root>
</file>

显然,这里假定两个根分支之间的1:1对应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM