Skip to content

QuickXmlWrite

Cinchoo edited this page Jun 20, 2017 · 6 revisions

Writing Xml file

To generate Xml file, use the ChoXmlWriter component to generate it. Sample below shows how to create Xml file (Emp.xml)

<Employees>
  <Employee>
    <Id>1</Id>
    <Name>Mark</Name>
  </Employee>
  <Employee>
    <Id>2</Id>
    <Name>Jason</Name>
  </Employee>
</Employees>

Write list of objects

List<ExpandoObject> objs = new List<ExpandoObject>();
dynamic rec1 = new ExpandoObject();
rec1.Id = 1;
rec1.Name = "Mark";
objs.Add(rec1);
 
dynamic rec2 = new ExpandoObject();
rec2.Id = 2;
rec2.Name = "Jason";
objs.Add(rec2);
 
using (var parser = new ChoXmlWriter("Emp.xml").WithXPath("Employees/Employee"))
{
    parser.Write(objs);
}

Write each object

using (var parser = new ChoXmlWriter("Emp.xml").WithXPath("Employees/Employee"))
{
    dynamic rec1 = new ExpandoObject();
    rec1.Id = 1;
    rec1.Name = "Mark";
    parser.Write(item);

    dynamic rec1 = new ExpandoObject();
    rec1.Id = 2;
    rec1.Name = "Jason";
    parser.Write(item);
}

Write using POCO object

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}
List<Employee> objs = new List<Employee>();
objs.Add(new Employee() { Id = 1, Name = "Tom" });
objs.Add(new Employee() { Id = 2, Name = "Mark" });

using (var parser = new ChoXmlWriter<Employee>("Emp.xml").WithXPath("Employees/Employee"))
{
    parser.Write(objs);
}

Please visit below article for detailed walk-through of Xml file writer

Cinchoo ETL - Xml Writer