从XML转换为CSV [英] Convert from XML to CSV
问题描述
我一直在寻找将XML转换为CSV的解决方案,但由于XML结构不同,我找不到适合我情况的解决方案
I have been searching for the solution to convert XML into CSV, but I cannot find one which matches my case as XML structure is different
XML结构看起来像
<VWSRecipeFile>
<EX_Extrusion User="ABC" Version="1.0" Description="" LastChange="41914.7876341204">
<Values>
<C22O01_A_TempFZ1_Set Item="A_TempFZ1_Set" Type="4" Hex="42700000" Value="60"/>
<C13O02_A_TempHZ2_Set Item="A_TempHZ2_Set" Type="4" Hex="43430000" Value="195"/>
<C13O03_A_TempHZ3_Set Item="A_TempHZ3_Set" Type="4" Hex="43430000" Value="195"/>
</Values>
</EX_Extrusion>
</VWSRecipeFile>
期望的CSV格式
A_TempFZ1_Set,A_TempHZ2_Set,A_TempHZ3_Set
A_TempFZ1_Set,A_TempHZ2_Set,A_TempHZ3_Set
60,195,195
60,195,195
我可以实现预期的新csv格式,但是不知道这是否是最好的csv格式,任何建议都会受到赞赏
i can achieve the new expected csv format, but don't know if it is the best way to do it, any suggestion is appreciated
'
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="no"/>
<xsl:template match="/VWSRecipeFile">
<xsl:for-each select="EX_Extrusion/Values/*">
<xsl:value-of select="concat(@Item,',')" />
</xsl:for-each>
<xsl:text>
</xsl:text>
<xsl:for-each select="EX_Extrusion/Values/*">
<xsl:value-of select="concat(@Value,',')" />
</xsl:for-each>
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>'
谢谢
推荐答案
一种实现此目的的方法是使用XSLT,该语言旨在与XML一起使用.您当然可以用C#解析XML,但是我喜欢XSLT,因为它更干净.
One way you can do this is to use XSLT, the language designed to work with XML. You surely can parse the XML with C# but I like XSLT cause it's cleaner.
您定义一个外部XSLT文件,然后在C#中调用它进行转换.
You define an external XSLT file, then call it within C# to do the transform.
修改:根据新要求添加了新列.
added new columns based on new requirements.
文件C:\ XmlToCSV.xslt(& #xA;
是换行符)
File C:\XmlToCSV.xslt (

is the newline character)
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="no"/>
<xsl:template match="/VWSRecipeFile">
<xsl:variable name="User" select="EX_Extrusion/@User"/>
<xsl:variable name="Version" select="EX_Extrusion/@Version"/>
<xsl:variable name="Description" select="EX_Extrusion/@Description"/>
<xsl:variable name="LastChange" select="EX_Extrusion/@LastChange"/>
<xsl:text>Item,Type,Hex,Value,User,Version,Description,LastChange
</xsl:text>
<xsl:for-each select="EX_Extrusion/Values/*">
<xsl:value-of select="concat(@Item,',',@Type,',',@Hex,',',@Value,',',$User,',',$Version,',',$Description,',',$LastChange,'
')"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
通过 XslCompiledTransform
应用转换:
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("C:\\XmlToCSV.xslt");
xslt.Transform("InputFile.xml", "OutputFile.csv");
根据您的需要进行调整.
Adjust it based on your needs.
这篇关于从XML转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!