如何将List <string>转换为xml文档?</string>

时间:2013-09-10 04:52:43

标签: c# xml

我有这个当前代码:

List<string> BugWSResponseList1 = new List<string>();
Logger.Write("\n\n" + DateTime.Now + " : " + 
             " : START : Creation of a set of Bugs via bug.Add API");
BugWSResponseList1 = CreateBugs(FilePath_EXPRESS_API_BugAdd_CreateBugs_DataFile);

我想将List<string> BugWSResponseList1转换为xml文档。

你能建议一种方法吗?

4 个答案:

答案 0 :(得分:3)

你可以很容易地使用LINQ:

var x = new XElement("bugs", 
    BugWSResponseList1.Select(t => new XElement("bug", t)));

Console.WriteLine(x.ToString());

答案 1 :(得分:2)

如果您将列表存储在类中,您可以编写如下内容:

[XmlType("Foo")]
public class Foo {

  [XmlArray("Items")]
  [XmlArrayItem("Item")]
  public List<string> Data {get; set;}

}

这将导致类似:

<Foo>
  <Items>
    <Item>Rock</Item>
    <Item>Paper</Item>
    <Item>Scissor</Item>
    <Item>Lizard</Item>
    <Item>Spock</Item>
  </Items>
</Foo>

答案 2 :(得分:2)

使用Linq to xml

using System.Xml.Linq;

XElement xml = new XElement("BugWSResponses",
                   (from x in BugWSResponseList1 select
                    new XElement("Bug", x)));

答案 3 :(得分:1)

代码示例

List<string> ExampleList = new List<string>{"1", "b"};

var xml = ExampleList.SerializeToXml();

序列化程序

public static string SerializeToXml<T>(this T obj)
{
    var serializer = new DataContractSerializer(obj.GetType());
    using (var writer = new StringWriter())
    using (var stm = new XmlTextWriter(writer))
    {
        serializer.WriteObject(stm, obj);
        return writer.ToString();
    }
}

结果

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"><string>1</string><string>b</string></ArrayOfstring>