简体   繁体   English

通过XSLT将XML转换为平面文件

[英]XML to flat file via XSLT

trying to convert an XML file of the following sort to a flat file or csv. 尝试将以下类型的XML文件转换为平面文件或csv。 I am able to generate XSLT files for other XML formats, but I don't really understand how to work with trees structure in this format. 我能够为其他XML格式生成XSLT文件,但我真的不明白如何使用这种格式的树结构。 Any thoughts? 有什么想法吗? I've experimented a bit, but I'm just not familiar with XSLT enough. 我已经尝试了一下,但我对XSLT不够熟悉。

  <observations 
        realtime_start="2013-02-08" 
        realtime_end="2013-02-08"  
        observation_start="1776-07-04" 
        observation_end="9999-12-31" units="lin"   
        output_type="2"  
        file_type="xml" 
        order_by="observation_date" 
        sort_order="asc" 
        count="792" offset="0"        
        limit="100000">
    <observation date="1947-01-01" CPIAUCSL_20130208="21.48"/>
    <observation date="1947-02-01" CPIAUCSL_20130208="21.62"/>
    <observation date="1947-03-01" CPIAUCSL_20130208="22.0"/>
  </observations>

Will this example suffice? 这个例子会满足吗?

T:\ftemp>type obs.xml
<?xml version="1.0" encoding="UTF-8"?>
  <observations realtime_start="2013-02-08" realtime_end="2013-02-08"
  observation_start="1776-07-04" observation_end="9999-12-31" units="lin"
  output_type="2" file_type="xml" order_by="observation_date" sort_order="asc"
  count="792" offset="0"        limit="100000">
  <observation date="1947-01-01" CPIAUCSL_20130208="21.48"/>
  <observation date="1947-02-01" CPIAUCSL_20130208="21.62"/>
  <observation date="1947-03-01" CPIAUCSL_20130208="22.0"/>
  </observations>

T:\ftemp>xslt obs.xml obs.xsl obs.csv

T:\ftemp>type obs.csv
date,CPIAUCSL
1947-01-01,21.48
1947-02-01,21.62
1947-03-01,22.0

T:\ftemp>type obs.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

<xsl:output method="text"/>

<xsl:template match="observations">
  <xsl:text>date,CPIAUCSL&#xa;</xsl:text>
  <xsl:for-each select="observation">
    <xsl:value-of select="@date"/>,<xsl:value-of select="@CPIAUCSL_20130208"/>
    <xsl:text>&#xa;</xsl:text>
  </xsl:for-each>
</xsl:template>

</xsl:stylesheet>
T:\ftemp>

The key to outputting text is that what gets serialized to the file are all of the text nodes of the result tree. 输出文本的关键是序列化到文件的是结果树的所有文本节点。 Any element or attribute nodes in the result tree are ignored, so don't even bother trying to create them ... just create text nodes and they all get concatenated into the output. 结果树中的任何元素或属性节点都会被忽略,所以甚至不用去尝试创建它们......只需创建文本节点,它们都会连接到输出中。

To go in the other direction, from CSV to XML, I've made the http://www.CraneSoftwrights.com/resources/#csv package freely available (and it works for TSV files as well) for use with XSLT 2.0. 为了进入另一个方向,从CSV到XML,我已经免费提供http://www.CraneSoftwrights.com/resources/#csv包(并且它也适用于TSV文件),以便与XSLT 2.0一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM