我正在努力将对象转换为csv。这是我的课程:
[XmlRoot(ElementName = "text")]
public class Text
{
[XmlElement(ElementName = "sentence")]
public List<Sentence> Sentences { get; set; }
}
[XmlRoot(ElementName = "sentence")]
public class Sentence
{
[XmlElement(ElementName = "word")]
public List<string> Words { get; set; }
}
此处的Xml属性是由于指定了Text对象必须同时序列化为xml和csv的规范。解析为xml没什么问题,但是我无法成功实现将其解析为csv格式。我曾尝试使用CsvHelper库解决该问题,但Text对象中的两个嵌套列表会引起一些问题。
例如,我有xml之类的
<?xml version="1.0" encoding="utf-8"?>
<text xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<sentence>
<word>dont</word>
<word>I</word>
<word>like</word>
<word>tomatoes</word>
</sentence>
<sentence>
<word>brother</word>
<word>loves</word>
<word>My</word>
<word>them</word>
</sentence>
</text>
所需的csv输出如下所示:
Word0, Word1, Word2, Word3
dont, I, like, tomatoes
brother, loves, My, them
提前谢谢
答案 0 :(得分:0)
这是使用XmlSerializer的示例
[XmlRoot(ElementName = "text")]
public class Text
{
[XmlElement(ElementName = "sentence")]
public List<Sentence> Sentences { get; set; }
}
[XmlRoot(ElementName = "sentence"), XmlType("sentence")]
public class Sentence
{
[XmlElement(ElementName = "word")]
public List<string> Words { get; set; }
}
using (FileStream fs = new FileStream(@"C:\w1\sampleXml1.xml", FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(Text));
var t = (Text)serializer.Deserialize(fs);
List<string> list = new List<string>();
string[] header = { "Word0", "Word1", "Word2", "Word3" };
list.Add(string.Join(",", header));
foreach (var item in t.Sentences)
{
list.Add(String.Join(",", item.Words));
}
File.WriteAllLines(@"C:\w1\output.csv", list);
}