合并多个XML文件中的选定元素

时间:2015-11-14 21:54:40

标签: xml xslt

我试图从具有完全相同格式的225个不同文件中获取相同的元素,并使用XSL将其合并到一个文件中。每个文件都是这样的:

<thickness_metafile>
  <job_bundle>
        <analysis_description>
             <material_table>
                material
              </material_table>
              <thickness_set>
                 ray element 1
                 ray element 2
                 ray element 3 
              </thickness_set>
        </analysis_description>
 </job_bundle>

因为每个文件的所有内容都是相同的,除了部分之外,我想复制最后224个文件中的每个thickness_set并将它们粘贴到第一个thickness_set下面的第一个文件中。基本上,我希望输出看起来像这样:

<thickness_metafile>
  <job_bundle>
        <analysis_description>
             <material_table>
                material
              </material_table>
              <thickness_set>
                 ray element 1
                 ray element 2
                 ray element 3 
              </thickness_set>
              <thickness_set>
                 ray element 4
                 ray element 5
                 ray element 6 
              </thickness_set>
              <thickness_set>
                 ray element 7
                 ray element 8
                 ray element 9 
              </thickness_set>
        </analysis_description>
 </job_bundle>

最终编辑的文件中应该有225个厚度集。我已经尝试了一些事情并取得了一些成功,但输出并没有像我喜欢的那样格式化。

1 个答案:

答案 0 :(得分:0)

假设我们的xml文件名为&#34; file1.xml&#34;,&#34; file2.xml&#34;,&#34; file3.xml&#34;等等。我们可以使用递归模板调用在xsl中处理它们:

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

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

    <xsl:template match="thickness_set">
        <xsl:copy>
            <xsl:value-of select="."/>
        </xsl:copy>
        <xsl:call-template name="file-loop">
            <!-- continue with file number 2 -->
            <xsl:with-param name="count" select="2"/>
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="file-loop">
        <xsl:param name="count"/>

        <!-- no more than 226 files -->
        <xsl:if test="$count &lt; 226">
            <thickness_set>
                <xsl:variable name="fi" select="document(concat('file',$count,'.xml'))"/>
                <xsl:value-of select="$fi//thickness_set"/>
            </thickness_set>
            <xsl:call-template name="file-loop">
                <xsl:with-param name="count" select="$count+1"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>

</xsl:stylesheet>

我们在xsl中传递的第一个xml文件(带有任何名称)。其他人,名字&#34; file2.xml&#34;等等,会自动加载。

相关问题