Reputation: 31
I have this current code:
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);
I would like to convert the List<string> BugWSResponseList1
to an xml document.
Can you please suggest a way to do it?
Upvotes: 2
Views: 9442
Reputation: 3109
code example
List<string> ExampleList = new List<string>{"1", "b"};
var xml = ExampleList.SerializeToXml();
The serializer
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();
}
}
results in
<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>
Upvotes: 1
Reputation: 9764
Use Linq to xml
using System.Xml.Linq;
XElement xml = new XElement("BugWSResponses",
(from x in BugWSResponseList1 select
new XElement("Bug", x)));
Upvotes: 2
Reputation: 103575
You can quite easily use LINQ for this:
var x = new XElement("bugs",
BugWSResponseList1.Select(t => new XElement("bug", t)));
Console.WriteLine(x.ToString());
Upvotes: 5
Reputation: 477804
If you store the list in a class you can write something like:
[XmlType("Foo")]
public class Foo {
[XmlArray("Items")]
[XmlArrayItem("Item")]
public List<string> Data {get; set;}
}
This will result in something like:
<Foo>
<Items>
<Item>Rock</Item>
<Item>Paper</Item>
<Item>Scissor</Item>
<Item>Lizard</Item>
<Item>Spock</Item>
</Items>
</Foo>
Upvotes: 2