2

我有这个当前代码:

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

4 回答 4

5

您可以很容易地为此使用 LINQ:

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

Console.WriteLine(x.ToString());
于 2013-09-10T04:58:30.777 回答
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>
于 2013-09-10T04:58:17.367 回答
2

使用Linq 转 xml

using System.Xml.Linq;

XElement xml = new XElement("BugWSResponses",
                   (from x in BugWSResponseList1 select
                    new XElement("Bug", x)));
于 2013-09-10T05:00:43.113 回答
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>
于 2013-09-10T05:03:38.190 回答