web-dev-qa-db-fra.com

Comment sérialiser une liste <T> en XML?

Comment convertir cette liste:

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

dans ce XML:

<Branches>
    <branch id="1" />
    <branch id="2" />
    <branch id="3" />
</Branches>
18
Ujjwal27

Vous pouvez essayer ceci en utilisant 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();

Production:

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

Oublié de mentionner: vous devez inclure l'espace de noms using System.Xml.Linq;.

MODIFIER:

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

production:

<Branches>
  <branch id="1" />
  <branch id="2" />
  <branch id="3" />
</Branches>
30
Praveen

Vous pouvez utiliser 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);

Ou créez la structure de classe appropriée et utilisez Sérialisation XML .

[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());
}
9
Dustin Kingen