从IList创建XML文件

问题描述 投票:0回答:3

我有一个IList可以合作。

我可以遍历列表中的行并从中创建XML文件吗?如果是这样我怎么去做呢?

我一直试图掌握XDocument,但我没有看到如何使用这种方法循环IList。

c# ilist
3个回答
1
投票

如果你想要KISS,请将System.Xml.Serialization添加到项目的参考文献中:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

public class Program {
    static void Main() {
        List<string> Data=new List<string> { "A","B","C","D","E" };

        XmlSerializer XMLs=new XmlSerializer(Data.GetType());
        XMLs.Serialize(Console.Out,Data);

        Console.ReadKey(true);
    }
}

我使用Console.Out给你一个快速的单行示例,但你可以选择任何Stream,很可能是一个要写入的文件。


1
投票

分为两行:

IList<string> list  = new List<string> {"A", "B", "C"};
var doc = new XDocument(new XElement("Root", list.Select(x => new XElement("Child", x))));

不要忘记使用:

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

如果原始的IList是非通用的IList,你需要包括对Enumerable.Cast<T>()的调用,以便Select()可以工作。例如。:

IList list  = new List<string> {"A", "B", "C"};
var doc = new XDocument(new XElement("Root",
    list.Cast<string>().Select(x => new XElement("Child", x))));

0
投票

如果您只是从一个字符串列表中找到一个相当简单的结构,那么这将起作用:

var list = new List<string> { "Joe", "Jim", "John" };

var document = new XDocument();
var root = new XElement("Root");
document.Add(root);
list.ForEach(x => root.Add(new XElement("Name", x)));
© www.soinside.com 2019 - 2024. All rights reserved.