使用 XSLT 将 XML 拆分为多个文件 [英] Splitting XML into multiple files with XSLT

查看:39
本文介绍了使用 XSLT 将 XML 拆分为多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难用 XSLT 来解决问题,但我听说可以将一个 XML 文件拆分为多个文件.基本上我想将所有元素复制到第一个文件和最后一个文件之后,然后为每个输出文件添加单独的文件内容.

I'm having a hard time wrapping my head around XSLT but I heard it's possible to split an XML file into multiple files. Basically I'd like to copy all the elements up to the first file and after the last file and then add the individual file content for each output file.

如果可能的话,有人能给我一些建议吗?

Could someone give me some pointers on this if it's even possible?

谢谢,

complete.xml

<rootelem>
  <elem>
    <file attr1='1'>
      <content>content file 1</content>
    </file>
    <file attr2='2'>
      <content>content file 2</content>
    </file>
    <file attr3='3'>
      <content>content file 3</content>
    </file>
  </elem>
</rootelem>

输出:

complete_PART1.xml

<rootelem>
  <elem>
     <file attr1='1'>
        <content>content file 1</content>
     </file>
  </elem>
</rootelem>

complete_PART2.xml

<rootelem>
  <elem>
    <file attr2='2'>
      <content>content file 2</content>
    </file>
  </elem>
</rootelem>

complete_PART3.xml

<rootelem>
  <elem>
     <file attr3='3'>
        <content>content file 3</content>
     </file>
  </elem>
</rootelem>

推荐答案

正在回复您对@Dimitre 的回答的评论...

Responding to your comment on @Dimitre's answer...

你写的,

<xsl:template match="/">
  <xsl:for-each select="elem/file">
    <xsl:result-document method="xml" href="file_{@id}-output.xml">
      <xsl:copy-of select="."/>
    </xsl:result-document>
  </xsl:for-each>
</xsl:template> 

这与您的 XML 不太匹配,其中 rootelem 作为最外层元素,而您的评论说 root 作为最外层元素.你可能想要这样的东西:

This doesn't quite match your XML, which has rootelem as an outermost element, and your comment says root as an outermost element. You probably want something like this:

<xsl:template match="/root">
  <xsl:for-each select="elem/file">
    <xsl:result-document method="xml" href="file_{@id}-output.xml">
      <root>
        <xsl:copy-of select="/root/@*" />
        <elem>
          <xsl:copy-of select="../@* | ." />
        </elem>
      </root>
    </xsl:result-document>
  </xsl:for-each>
</xsl:template> 

你可以变得更有趣,尝试使用 <xsl:copy> 而不是 root 和 elem 的字面结果元素,但它似乎不值得付出努力,除非它们会有所不同.

You could get fancier, trying to use <xsl:copy> instead of literal result elements for root and elem, but it doesn't seem worth the effort unless they're going to vary.

这篇关于使用 XSLT 将 XML 拆分为多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆