Donate

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.
<?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.
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.
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. Create XmlElement Using XmlSerializer in C#.NET

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.