2013-06-11 11 views
11

Jak przekonwertować tę listę:Jak serializować listę <T> na XML?

List<int> Branches = new List<int>(); 
Branches.Add(1); 
Branches.Add(2); 
Branches.Add(3); 

do tego XML:

<Branches> 
    <branch id="1" /> 
    <branch id="2" /> 
    <branch id="3" /> 
</Branches> 
+2

Rozpocznij tu potem wrócić z konkretnym pytaniem: http://msdn.microsoft.com/en-us/library/system.xml.serialization.aspx –

Odpowiedz

24

można spróbować to przy użyciu LINQ:

List<int> Branches = new List<int>(); 
Branches.Add(1); 
Branches.Add(2); 
Branches.Add(3); 

XElement xmlElements = new XElement("Branches", Branches.Select(i => new XElement("branch", i))); 
System.Console.Write(xmlElements); 
System.Console.Read(); 

wyjściowa:

<Branches> 
    <branch>1</branch> 
    <branch>2</branch> 
    <branch>3</branch> 
</Branches> 

Zapomniałem wspomnieć: musisz dodać przestrzeń nazw using System.Xml.Linq;.

EDIT:

XElement xmlElements = new XElement("Branches", Branches.Select(i => new XElement("branch", new XAttribute("id", i))));

wyjściowa:

<Branches> 
    <branch id="1" /> 
    <branch id="2" /> 
    <branch id="3" /> 
</Branches> 
+4

To nie wyjście ' 'wyświetli' '. – James

+1

Czy chodziło Ci o 'nowy XElement (" branch ", nowy XAttribute (" id ", i))' – lisp

+0

@ James, @ lisp Dzięki za poprawienie mnie. Poprawiłem moją odpowiedź. – Praveen

5

Można użyć Linq-to-XML

List<int> Branches = new List<int>(); 
Branches.Add(1); 
Branches.Add(2); 
Branches.Add(3); 

var branchesXml = Branches.Select(i => new XElement("branch", 
                new XAttribute("id", i))); 
var bodyXml = new XElement("Branches", branchesXml); 
System.Console.Write(bodyXml); 

Albo stworzyć odpowiednie struktury klasowej i używać XML Serialization.

[XmlType(Name = "branch")] 
public class Branch 
{ 
    [XmlAttribute(Name = "id")] 
    public int Id { get; set; } 
} 

var branches = new List<Branch>(); 
branches.Add(new Branch { Id = 1 }); 
branches.Add(new Branch { Id = 2 }); 
branches.Add(new Branch { Id = 3 }); 

// Define the root element to avoid ArrayOfBranch 
var serializer = new XmlSerializer(typeof(List<Branch>), 
            new XmlRootAttribute("Branches")); 
using(var stream = new StringWriter()) 
{ 
    serializer.Serialize(stream, branches); 
    System.Console.Write(stream.ToString()); 
} 
Powiązane problemy