XML包含来自另一个xml的元素

时间:2014-07-10 11:54:37

标签: xml xslt xml-dtd

所以我们有一个xml文件:

EnglandCities.xml

<Cities>
    <City Name="London">
        other children
    </City>
    <City Name="Southampton">
        other children
    </City>
</Cities>

现在我们需要第二个文件说: UKCities.xml

<Cities>
    <City Name="London">
        other children
    </City>
    <City Name="Southampton">
        other children
    </City>
    <City Name="Belfast">
        other children
    </City>
    <City Name="Edinburgh">
        other children
    </City>
</Cities>

此UKCities.xml有新条目“Belfast”&amp; “爱丁堡”。

我们可以在UKCities.xml中使用xml:include(或类似的东西)来获取“伦敦”和“来自EnglandCities.xml的“Southampton”元素而不是键入它们? 如下所示:

<Cities>
    <xml:include file="EnglandCities.xml"/>
    <City Name="Belfast">
        other children
    </City>
    <City Name="Edinburgh">
        other children
    </City>
</Cities>

1 个答案:

答案 0 :(得分:2)

您已将此标记为“xslt”,这表明您可能对XSLT解决方案感兴趣。 (如果不是这种情况,请删除标签,我将删除此答案。)

但假设您可以使用XSLT,您可以使用 document()函数来引用XSLT中的“EnglandCities.xml”

<xsl:copy-of select="document('EnglandCities.xml')/*/*" />

或者也许(如果您使用的是Identity Transform ....)

<xsl:apply-templates select="document('EnglandCities.xml')/*/*" />

试试这个XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:param name="include" select="'EnglandCities.xml'" />

  <xsl:template match="/*">
    <xsl:copy>
      <xsl:apply-templates select="document($include)/*/*" />
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

当应用于原始XML时,输出以下内容

<Cities>
  <City Name="London">
        other children
    </City>
  <City Name="Southampton">
        other children
    </City>
    <City Name="Belfast">
        other children
    </City>
    <City Name="Edinburgh">
        other children
    </City>
</Cities>