如何从xml中获取多个元素并将值写为csv

时间:2013-11-14 07:14:52

标签: c# xml

从以下xml中,必须获取名称回归和烟雾,并在输出中将其写为回归,烟雾。

<categories>
        <category name="Regression" />
        <category name="Smoke" />
</categories>

2 个答案:

答案 0 :(得分:0)

这是使用linq到xml的划痕:

XDocument doc = XDocument.Load(@"<path to your xml file>");
var names = doc.Elements("category").Select(e => (string)e.Attribute("name"));
var csv = string.Join(",", names);

答案 1 :(得分:0)

如果您想要的只是读取xml类别名称值并将其写入带有逗号作为分隔符的文本文件,则应执行以下操作:

///step1: read all the elements attribute value
XDocument doc = XDocument.Parse(xml);
var data = doc.Descendants("category")
                      .Select(s=>s.Attribute("name").Value)
                      .ToList();

///step2: write the read value to the file
using (StreamWriter writer = new StreamWriter("d://csv.txt", true))
{
    writer.WriteLine(string.Join(",", data));
}
//or simply
//File.WriteAllText("d://csv.txt", string.Join(",", data));

如果您想创建一个标准的CSV文件,其中包含正确的标题和所有内容,您可以找到大量代码,其中大部分代码都是在SO中执行此操作。看看this