2013-06-11 10 views
11

Come convertire questa lista:Come serializzare un elenco <T> in XML?

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

in questo XML:

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

Inizia da qui poi tornare con una domanda specifica: http://msdn.microsoft.com/en-us/library/system.xml.serialization.aspx –

risposta

24

Si può provare questo utilizzando 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(); 

uscita:

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

Ho dimenticato di menzionare: è necessario includere lo spazio dei nomi using System.Xml.Linq;.

EDIT:

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

uscita:

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

Questo non emetterà ' 'emetterà' '. – James

+1

Intendevi 'nuovo XElement (" ramo ", nuovo XAttribute (" id ", i))' – lisp

+0

@ James, @ lisp Grazie per avermi corretto. Ho corretto la mia risposta. – Praveen

5

È possibile utilizzare 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); 

o creare la struttura di classe appropriata e utilizzare 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()); 
} 
Problemi correlati