How to convert this list:
List<int> Branches = new List<int>();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);
into this XML:
<Branches>
<branch id="1" />
<branch id="2" />
<branch id="3" />
</Branches>
A List can be serialized—here we serialize (to a file) a List of objects. Serialize notes. The next time the program runs, we get this List straight from the disk. We see an example of BinaryFormatter and its Serialize methods.
XML Serialization Considerations Type identity and assembly information are not included. Only public properties and fields can be serialized. Properties must have public accessors (get and set methods). If you must serialize non-public data, use the DataContractSerializer class rather than XML serialization.
XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.
You can try this using 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();
Output:
<Branches>
<branch>1</branch>
<branch>2</branch>
<branch>3</branch>
</Branches>
Forgot to mention: you need to include using System.Xml.Linq;
namespace.
EDIT:
XElement xmlElements = new XElement("Branches", Branches.Select(i => new XElement("branch", new XAttribute("id", i))));
output:
<Branches>
<branch id="1" />
<branch id="2" />
<branch id="3" />
</Branches>
You can use 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);
Or create the appropriate class structure and use 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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With