【问题标题】:merge two xml files using xslt使用 xslt 合并两个 xml 文件
【发布时间】:2012-09-07 13:56:50
【问题描述】:

我想使用 xslt 将两个 xml 文件合并为一个。

file1:

<cut> <content1> .... </content1> </cut>

file1:

<cut> <content2> .... </content2> </cut>

merged:
<cut>
<content1> ... </content1>
<content2> ... </content2>
</cut>

我想将参数传递给包含要合并的文件的 xslt。

xsltproc.exe" --stringparam file1 s:\file1.xml --stringparam file2 s:\file2.xml s:\merge.xslt

merge.xslt:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:exsl="http://exslt.org/common"
    extension-element-prefixes="exsl">

  <xsl:output indent="yes" omit-xml-declaration="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="file1"/>
  <xsl:param name="file2"/>

  <xsl:variable name="big-doc-rtf">
    <xsl:copy-of select="document($file1)"/>
    <xsl:copy-of select="document($file2)"/>
  </xsl:variable>

  <xsl:variable name="big-doc" select="exsl:node-set($big-doc-rtf)"/>

  <xsl:template match="/">
    <cut>
      <xsl:apply-templates select="$big-doc/cut/*"/>
    </cut>
  </xsl:template>

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

  <xsl:template match="@*|text()|comment()|processing-instruction()">
    <xsl:copy-of select="."/>
  </xsl:template>

</xsl:stylesheet>

我只得到一个空的“cut”标签。怎么了?

【问题讨论】:

    标签: xml xslt parameters


    【解决方案1】:

    不使用 xsltproc 而是 xmllint

    (编辑:xsltproc 也允许 xinclude)

    --xinclude : 对文档输入进行 XInclude 处理

    x1.xml

    <cut><content1>content1</content1></cut>
    

    x2.xml

    <cut><content2>content2</content2></cut>
    

    x3.xml

    <?xml version="1.0"?>
    <cut xmlns:xi="http://www.w3.org/2003/XInclude">
      <xi:include href="x1.xml" parse="xml" xpointer="xpointer(/cut/content1)"/>
      <xi:include href="x2.xml" parse="xml" xpointer="xpointer(/cut/content2)"/>
    </cut>
    

    运行:

    $ xmllint -xinclude  x3.xml 
    <?xml version="1.0"?>
    <cut xmlns:xi="http://www.w3.org/2003/XInclude">
      <content1>content1</content1>
      <content2>content2</content2>
    </cut>
    

    【讨论】:

      【解决方案2】:

      无法重现问题

      很可能您的代码中的两个 document() 函数都返回“nothing”——这意味着用作每个调用的第一个参数的 URI 不标识文件(无法找到/解析文件),或者该文件不包含格式正确的 XML 文档。

      【讨论】:

        【解决方案3】:

        这对我来说很好用,在 document() 调用中使用硬编码路径的 xalan 和 saxon 解析器。问题可能是由于某种原因,您的 xsl 没有看到您的文档。

        我怀疑源文档中的 xml 是否存在问题,因为这可能会引发错误。

        【讨论】:

          猜你喜欢
          • 2013-10-02
          • 1970-01-01
          • 2019-08-25
          • 1970-01-01
          • 1970-01-01
          • 2019-01-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多