Home > Software design >  Generate xml file using c#
Generate xml file using c#

Time:01-24

I want to generate an xml file using serialization in c#. I'm new to this language. So please give a hint.

My xml file has content as-

<Employees>
    <Employee>
      <Emp id="1" name="Ajay" salary="20000"></Emp>
      <Emp id="2" name="Vinay" salary="25000"></Emp>
      <Emp id="3" name="Jay" salary="23000"></Emp>
    </Employee>
</Employees>

CodePudding user response:

Define POCO matching your expected xml text (Sample below)

public class Employees
{
    [XmlArray("Employee")]
    [XmlArrayItem(typeof(Emp), ElementName="Emp")]
    public Emp[] Emps { get; set; }
}

public class Emp
{
    [XmlAttribute("id")]
    public int Id { get; set; }
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlAttribute("salary")]
    public string Salary { get; set; }
}

Then construct objects and use XmlSerialier to serialize them

public static void SerializeXml()
{
    Employees emps = new Employees()
    {
        Emps = new Emp[]
        {
            new Emp
            {
                Id = 1,
                Name = "Ajay",
                Salary = "23000",
            }
        }
    };
    
    XmlSerializer s = new XmlSerializer(typeof(Employees));
    
    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
    namespaces.Add(string.Empty, string.Empty); 
    
    XmlWriterSettings settings = new XmlWriterSettings
    {
        Indent = true,
        OmitXmlDeclaration = true
    };
    StringBuilder sb = new StringBuilder();
    TextWriter w = new StringWriter(sb);
    using (var writer = XmlWriter.Create(w, settings))
    {
        s.Serialize(writer, emps, namespaces);
    }       
    
    Console.WriteLine(sb.ToString());
} 

Sample fiddle: https://dotnetfiddle.net/c4nMwr

  •  Tags:  
  • Related