我有多个.xml文件,它们都有相同的节点名称,但值不同。示例:
File1.xml有以下内容:
<?xml version="1.0"?><Data><Waf>No</Waf><Name>TEMP\1</Name><Number>0</Number><Iteration>1</Iteration><Lot> </Lot><DateAndTime>11:36:24:35 10/8/2019</DateAndTime><Id>5555</Id><SW>6.40.22.10900</SW><Image>Reference Point 750</Image><Angle >0</Angle ><Algo></Algo></Data>类似地,File2.xml有:
<?xml version="1.0"?><Data><Waf>Yes</Waf><Name>TEMP\2</Name><Number>10</Number><Iteration>6</Iteration><Lot>99</Lot><DateAndTime>11:36:49:35 10/8/2019</DateAndTime><Id></Id><SW>6.40.22.10900</SW><Image>Reference Point 90</Image><Angle >180</Angle ><Algo></Algo></Data>我使用C# ( 2010);我的目标是获得一个具有第一行的.csv / .txt文件:
Waf, Name, Number, Iteration, Lot, DateAndTime, Id, SW, Image, Angle, Algo
No, TEMP\1, 0, 1, - , 11:36:24:35 10/8/2019, 5555, 6.40.22.10900, Reference Point 750, 0, -
Yes, TEMP\2 , 10, 6, 99, 11:36:49:35 10/8/2019, -, 6.40.22.10900, Reference Point 90, 180, - 我的算法的输入将是xml文件的名称。以下是我迄今所做的工作:
for (idx = 0; idx < num_files; idx++)
{
file_name = file_name + ".xml"; // this contains the name of xml file
if (idx == 0) // if I'm reading the first xml file, make a note of all the node names since they will be the column headers.
{
fs = new FileStream(location_xml_file, FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xml_num_nodes = xmldoc.n ; //.Count;
Console.Write("\n xml_num_nodes = {0}", xml_num_nodes);
}
}然而,
发布于 2019-11-26 10:13:58
使用xml编写非常简单的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FOLDER = @"c:\temp\";
const string CSV_FILENAME = @"c:\temp\test.csv";
static void Main(string[] args)
{
string[] xmlFiles = Directory.GetFiles(FOLDER, "*.xml");
StreamWriter writer = new StreamWriter(CSV_FILENAME);
Boolean firstLine = true;
for (int idx = 0; idx < xmlFiles.Length; idx++)
{
string file_name = xmlFiles[idx];
XDocument doc = XDocument.Load(file_name);
foreach(XElement data in doc.Descendants("Data"))
{
if (firstLine)
{
string[] headers = data.Elements().Select(x => x.Name.LocalName).ToArray();
writer.WriteLine(string.Join(",", headers));
firstLine = false;
}
string[] row = data.Elements().Select(x => (string)x).ToArray();
writer.WriteLine(string.Join(",", row));
}
}
writer.Flush();
writer.Close();
}
}
}发布于 2019-11-26 00:11:57
定义一个接受反序列化XML数据的类,然后将每个XML文件反序列化到类中,然后迭代类成员并将数据从每个成员写入CSV字符串,然后将CSV字符串写入输出CSV文件。
https://stackoverflow.com/questions/59041400
复制相似问题