Create XmlElement Using XmlSerializer In C#.NET
Given the XML data below, the product properties are generated below the products node. What I want is to structure the product properties inside an element Product while serializing.
To achieve that, I have modified the model classes by separating the properties into another class and in the Products class I created a property
of type List with XML Attribute Product.
Here's the code to generate the XML file.
As you can see from the output below, the properties are now inside the Product node.
<?xml version="1.0" encoding="utf-8"?> <Products xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Code>12345</Code> <Name>Samsung Galaxy</Name> <Model>Galaxy</Model> <Manufacturer>Samsung Ltd</Manufacturer> <OperatingSystem>Jelly Bean</OperatingSystem> <Distributor>Junrex</Distributor> <Version>7.0</Version> </Products>
public class Products { [XmlElement("Product")] public List<ProductProperties> MobileProperties; } public class ProductProperties { public string Code; public string Name; public string Model; public string Manufacturer; public string OperatingSystem; public string Distributor; public string Version; }
Products product = new Products(); product.MobileProperties = new List<ProductProperties>(); product.MobileProperties.Add(new ProductProperties() { Code = "12345", Distributor = "Junrex", Manufacturer = "Samsung Ltd", Model = "Galaxy", Name = "Samsung Galaxy", OperatingSystem = "Jelly Bean", Version = "7.0" }); XmlSerializer myserial = new XmlSerializer(typeof(Products)); StreamWriter swriter = new StreamWriter("ProductData.xml"); myserial.Serialize(swriter, product); swriter.Close(); StreamReader reader = new StreamReader("ProductData.xml"); RichTextBox1.Text = reader.ReadToEnd(); reader.Close();
Comments
Post a Comment