如何使用xslt将几个xml文件合并到一个xml文件中?

时间:2011-05-07 08:11:12

标签: xml xslt

我需要使用XSLT将几个XML文件合并为一个。我有4个XML文件发布,接收,theatre1和theatre2。必须首先添加版本,然后必须将匹配的接收放在发布部分内。然后应该添加另外两个。

这是文件的格式。 发布:  文本

接收:  文本

结果应该是: <  文本  文本

这是我到目前为止所做的,但它并没有完全奏效

                                                                                          

其他2个文件只需要在最后添加

2 个答案:

答案 0 :(得分:3)

以下是如何继续:

$ expand -t2 release.xml
<release name="bla"/>

$ expand -t2 reception.xml
<receptions>
  <reception name="bla">
    <blabla/>
  </reception>
  <reception name="blub">
    <blubbel/>
  </reception>
</receptions>

$ expand -t2 theatre1.xml
<theatre number="1"/>

$ expand -t2 theatre2.xml
<theatre number="2"/>

$ expand -t2 release.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:strip-space elements="*"/><!-- make output look nice -->
  <xsl:output indent="yes"/>

  <xsl:template match="release">
    <xsl:variable name="rel-name" select="@name"/>
    <xsl:copy>
      <xsl:copy-of select="node()"/><!-- copy remainder of doc -->
      <xsl:copy-of select="document( 'release.xml' )"/>
      <xsl:variable name="rcpt-doc" select="document( 'reception.xml' )"/>
      <xsl:copy-of select="$rcpt-doc/*/reception[ @name = $rel-name ]"/>
      <xsl:copy-of select="document( 'theatre1.xml' )"/>
      <xsl:copy-of select="document( 'theatre2.xml' )"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

这样称呼:

 xsltproc release.xsl release.xml

结果如下:

<?xml version="1.0"?>
<release>
  <release name="bla"/>
  <reception name="bla">
    <blabla/>
  </reception>
  <theatre number="1"/>
  <theatre number="2"/>
</release>

答案 1 :(得分:2)

Reading Multiple Input Documents似乎回答了这个问题。

  

当您运行XSLT处理器时,您可以告诉它在哪里找到源树文档 - 可能在本地或远程计算机上的磁盘文件中 - 以及要应用于它的样式表。您不能告诉处理器一次将样式表应用于多个输入文档。但是,document()函数允许样式表命名要读入的其他文档。您可以将整个文档插入结果树中,或者根据XPath表达式描述的条件插入部分文档。您甚至可以将此函数与xsl:key指令和key()函数一起使用,以在源文档外部的文档中查找键值。

因此,在xslt中加载多个文档的关键是使用document()函数。

相关问题