Saturday, May 7, 2016

Create XmlElement using XmlSerializer in .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.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?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>

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.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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;
}

Here's the code to generate the XML file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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();

As you can see from the output below, the properties are now inside the Product node.

0 comments:

Post a Comment