我应该如何去将XML转换成CSV(how should I go about converting

2019-10-17 09:49发布

我试图采取一些XML代码,样品低于:

  <time_report>

 <project_ID>4</project_ID>

 <project_status>close</project_status>

 <client_ID>6001</client_ID>

     <time_record>

            <project_start_time>15:02:33</project_start_time>

            <project_end_time>15:07:44</project_end_time>

            <project_total_time>PT00H05M11S</project_total_time>

     </time_record>

 <employee_ID>10001</employee_ID>

 <employee_name>Mary Beth</employee_name>

 <date_created>2009-08-25</date_created>

</time_report>

然后输出它,所以它是在以下格式:

project_id, project_status, client_id, project_start_time, project_end_time,  project_total_time, employee_ID, employee_name, date_created

4, close, 6001, 15:02:33, 15:07:44, PT00H05M11S, 10001, Mary Beth, 2009-08-25

我一直在试图用xmllint要做到这一点,但不幸未能取得任何进展,话说回来,我想知道是否有人会有一个建议,以我应该怎么办呢? 我会在bash / shell环境做这个。 任何帮助,将不胜感激,谢谢!

还忘了提,我能得到正确的结果,如果我打开XML在Excel文件了,然后保存为CSV,只是在寻找一种方式来做到这一点,在linux

    project_ID,project_status,client_ID,project_start_time,project_end_time,project_total_time,employee_ID,employee_name,date_created
4,close,6001,15:02:33,15:07:44,PT00H05M11S,10001,Mary Beth,8/25/2009
5,open,6003,12:00:00,12:45:00,PT00H45M00S,10003,Michelle,9/11/2009
2,close,6002,10:00:00,10:30:00,PT00H30M00S,10002,Joe,8/25/2009
2,open,6004,12:00:00,3:27:05,PT03H23M05S,10004,Mike,8/13/2009

Answer 1:

xmlstarlet是一个非常强大的命令行工具,它可以让你查询XML或运行XSLT转换。 这里也有一些XSLT XML-> CSV例子左右浮动,但下面的一行为您提供您所需要的:

xmlstarlet sel -B -t -m "//time_reports/time_report" -n -m "*" -v . -o , input.xml

唯一的问题是,我需要包裹<time_report>用称为根级别的标签<time_reports>



Answer 2:

要改变你的XML为CSV(如与xsltproc的),你可以使用XSL样式表是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" />
    <xsl:template match="/">
        <xsl:for-each select="//time_report[position()=1]/*">
            <xsl:if test="not(position()=1)">
                <xsl:text>,</xsl:text>
            </xsl:if>
            <xsl:value-of select="name()" />
        </xsl:for-each>
        <xsl:text>&#13;</xsl:text>
        <xsl:for-each select="//time_report">
            <xsl:for-each select="./*">
                <xsl:if test="not(position()=1)">
                    <xsl:text>,</xsl:text>
                </xsl:if>
                <xsl:value-of select="normalize-space(.)" />
            </xsl:for-each>
            <xsl:text>&#13;</xsl:text>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>


Answer 3:

你也可以用我的Xidel :(假设你有你的XML没有空字段)

 xidel /tmp/test.xml -e '//time_report/string-join(.//text()[normalize-space(.)], ", ")'

标准的XPath 2,无需记住不同的命令行参数的名称...

或者没有这样的假设:

 xidel /tmp/test.xml -e '//time_report/string-join(.//*[not(*)], ", ")'


文章来源: how should I go about converting xml into csv