我正在尝试将xml文件转换为csv文件。如何读取和解析xml文件并将其转换为csv?是否有任何软件包可以将xml转换为csv。
请给我编写代码的最佳方法。
如何在C#中将XML文件转换为CSV文件,仅显示以下标记:
<a:MarketingAllCardholder xmlns:b="http://schemas.datacontract.org/2004/07/ExternalClient.Data.Classes">
<b:MarketingAllCardholderData>
<b:CentreName>Corporate Office</b:CentreName>
<b:Country>Austria</b:Country>
<b:CustomerId>379</b:CustomerId>
<b:DOB>25/02/1991</b:DOB>
<b:Email>farah@gmail.com</b:Email>
<b:ExpiryDate>03/01/2020 08:01</b:ExpiryDate>
</b:MarketingAllCardholderData>
<b:MarketingAllCardholderData>
<b:CentreName>Corporate Office</b:CentreName>
<b:Country>Egypt</b:Country>
<b:CustomerId>988915</b:CustomerId>
<b:DOB>01/03/1986</b:DOB>
<b:Email>hesh.a.metwally@gmail.com</b:Email>
<b:ExpiryDate>07/01/2020 11:38</b:ExpiryDate>
</b:MarketingAllCardholderData>
输出CSV文件格式应如下:
标题,名字,姓氏,DOB,电子邮件,国家/地区,令牌,原始余额,到期日期 瓦西姆·沃西先生,1990年1月19日,wasim.warsi @ flcard.com,印度,384176,500,14 / 11/2019 05:31,14 / 11/2018 05:33,16.34
答案 0 :(得分:3)
基本上,您可以使用XMLSerializator或XSLT。
使用XMLSerializator:
public class MarketingAllCardholder{
public MarketingAllCardholderData[] marketingAllCardholderDataList { get; set; }
}
using System.IO;
using System.Xml.Serialization;
using (FileStream fs = new FileStream(@"name.xml", FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(MarketingAllCardholde[]));
var data = (MarketingAllCardholder[])serializer.Deserialize(fs);
List<string> list = new List<string>();
foreach (var item in data)
{
//Add All the necessary columns here...
//After the columns add the delimiter character -> string.Join(","....
}
File.WriteAllLines("D:\\csvFile.csv", list);
}
另一种方法是使用XSLT对其进行转换。
您在这里执行以下步骤
使用以下方法:
public static string ToCSV(string xmlTextDate, string xsltFile)
{
string result = string.Empty;
var xpathDoc = new XPathDocument(xmlTextDate);
var xsltTransform = new System.Xml.Xsl.XslCompiledTransform();
xsltTransform.Load(xsltFile);
using (MemoryStream ms = new MemoryStream())
{
var writer = new XmlTextWriter(ms, Encoding.UTF8);
using (var rd = new StreamReader(ms))
{
var argList = new System.Xml.Xsl.XsltArgumentList();
xsltTransform.Transform(xpathDoc, argList, writer);
ms.Position = 0;
result = rd.ReadToEnd();
}
}
return result;
}
并这样称呼
var csvString = ToCSV("name.xml","name.xsl");
答案 1 :(得分:0)
另一种方法是使用FileHelper
using (StreamReader r = new StreamReader(xmlfilepath))
{
string xmlString = r.ReadToEnd();
XmlSerializer ser = new XmlSerializer(typeof(MarketingAllCardholder));
using (TextReader reader = new StringReader(xmlString))
{
var marketingAllCardholder = (MarketingAllCardholder)ser.Deserialize(reader);
var engine = new FileHelperEngine<MarketingAllCardholderData>();
engine.HeaderText = engine.GetFileHeader();
string filePath = Path.Combine(@"C:\RnD", "testfile" + ".csv");
engine.WriteFile(filePath , (IEnumerable<MarketingAllCardholderData>)marketingAllCardholder.MarketingAllCardholderData);
}
}
来自XML的模型(您可以使用xmltocsharp将xml转换为c#模型)并添加[DelimitedRecord(",")]
[DelimitedRecord(",")]
[XmlRoot(ElementName = "MarketingAllCardholderData")]
public class MarketingAllCardholderData
{
[XmlElement(ElementName = "CentreName")]
public string CentreName { get; set; }
[XmlElement(ElementName = "Country")]
public string Country { get; set; }
[XmlElement(ElementName = "CustomerId")]
public string CustomerId { get; set; }
[XmlElement(ElementName = "DOB")]
public string DOB { get; set; }
[XmlElement(ElementName = "Email")]
public string Email { get; set; }
[XmlElement(ElementName = "ExpiryDate")]
public string ExpiryDate { get; set; }
}
[DelimitedRecord(",")]
[XmlRoot(ElementName = "MarketingAllCardholder")]
public class MarketingAllCardholder
{
[XmlElement(ElementName = "MarketingAllCardholderData")]
public List<MarketingAllCardholderData> MarketingAllCardholderData { get; set; }
}
答案 2 :(得分:0)
首先,您将要反序列化xml,以便使其数据易于读取和访问。为此,我建议您仅使用xmltocsharp之类的网站,它将生成您的类,然后您所要做的就是将它们粘贴到您的代码中。
完成此操作后,转换代码非常简单:
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
using (var reader = new StreamReader(xmlFilePath))
{
var envelope = ((Envelope)serializer.Deserialize(reader));
var csv_content = new List<string>();
var headers = new[] { "CentreName", "Country", "CustomerId", "DOB", "Email", "ExpiryDate" };
csv_content.Add(string.Join(",", headers));
foreach (var data in envelope.Body
.GetMarketingAllCardholderDataResponse
.GetMarketingAllCardholderDataResult
.MarketingAllCardholder
.MarketingAllCardholderData)
{
var row_data = new[]
{
data.CentreName,
data.Country,
data.CustomerId,
data.DOB,
data.Email,
data.ExpiryDate
};
csv_content.Add(string.Join(",", row_data));
}
File.WriteAllLines("csvFilePath.csv", csv_content);
}
答案 3 :(得分:0)
使用Cinchoo ETL-一个开放源代码库,您只需几行代码即可轻松进行转换
using (var r = new ChoXmlReader("*** XML FILE PATH ***")
.WithXPath("b:MarketingAllCardholderData")
.WithXmlNamespace("a", "schemas.datacontract.org/2004/07/ExternalClient.Responses")
.WithXmlNamespace("b", "schemas.datacontract.org/2004/07/ExternalClient.Data.Classes")
)
{
using (var w = new ChoCSVWriter(sb)
.WithFirstLineHeader()
.Configure(c => c.UseNestedKeyFormat = false)
)
w.Write(r);
}
Console.WriteLine(sb.ToString());
输出:
CentreName,Country,CustomerId,DOB,Email,ExpiryDate
Corporate Office,Austria,379,25/02/1991,farah@gmail.com,3/1/2020 8:01:00 AM
Corporate Office,Egypt,988915,01/03/1986,hesh.a.metwally@gmail.com,7/1/2020 11:38:00 AM
有关更多信息,请访问GitHub存储库
希望有帮助。
免责声明:我是这个图书馆的作者。