如果在第一个XML中设置了属性,则XSLT从第二个XML复制元素

时间:2015-06-08 10:55:35

标签: xml xslt xslt-1.0

我有以下输入XML:
car.xml:

<car ref-id="parts.xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <color>red</color>
  <tire>michelin</tire>
  <engines override="false">
    <engine>
      <model>Z</model>
    </engine>
  </engines>
  <hifi>pioneer</hifi>
</car>

parts.xml:

<?xml version="1.0" encoding="UTF-8"?>
<parts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <engines>
    <engine>
      <model>X</model>
    </engine>
    <engine>
      <model>Y</model>
    </engine>
  </engines>
  <tire>goodyear</tire>
  <color>black</color>
  <airbag>true</airbag>
</parts>

我想将parts.xml与car.xml合并,但是只想复制parts.xml中的那些节点(无论它们的值如何):

  • A,car.xml中不存在
  • B,存在于汽车xml中,但元素是 “override”属性设置为false。

Michael-hor257k为A提供了solution,但我实施了B。

然后XSLT看起来像这样:

         

<xsl:variable name="loc">
    <xsl:value-of select="car/@ref-id" />
</xsl:variable>

<xsl:template match="/car">
    <xsl:variable name="local-names">
        <xsl:for-each select="*">
            <name>
                <xsl:value-of select="name()" />
            </name>
            <attr>
                <xsl:value-of select="@override" />
            </attr>
        </xsl:for-each>
    </xsl:variable>

    <xsl:copy>
        <xsl:copy-of select="*" />
        <xsl:copy-of
            select="document($loc)/parts/*[not(name()=exsl:node-set($local-names)/name)] or 
                exsl:node-set($local-names)/attr='false'"/> 
    </xsl:copy>
</xsl:template>

我尝试添加

<attr>
  <xsl:value-of select="@override" />
</attr>

or exsl:node-set($local-names)/attr='false'到XSLT但没有成功。

2 个答案:

答案 0 :(得分:1)

You could change line #10 from:

<xsl:for-each select="*">

to:

<xsl:for-each select="*[not(@override='false')]">

You didn't post the expected result, so I am not sure it will be to your liking. This could prove much more complicated than it seems, if you need to merge nodes at different levels.

答案 1 :(得分:0)

变化:

        <attr>
            <xsl:value-of select="@override" />
        </attr>

要:

        <attr>
            <xsl:value-of select="engines/@override" />
        </attr>