Home > Software engineering >  convert List of string array into xml
convert List of string array into xml

Time:05-14

I need to convert list of array into xml. In the list the first object is the elements of the xml and from second object onwards it is the values of the elements.

For eg:

list[0]={"firstname","lastname","age","empid"}
list[1]={"john","maxwell","31","101"}
list[2]={"max","lee","45","102"}

Now using above list I need to create an XML file, as mentioned above list[0] needs to used as XML elements and list[1] & list[2] are values for those elements. final XML will look something like this:

<?xml version="1.0" encoding="UTF-8"?>
<EmployeeRecords>
    <Employee>      
        <firstname>john</firstname>
        <lastname>maxwell</lastname>
        <age>31</age>
        <empid>101</empid>
    </Employee>
    <Employee>
        <firstname>Max</firstname>
        <lastname>lee</lastname>
        <dob>45</dob>
        <empid>102</empid>
    </Employee>
</EmployeeRecords>

I have tried using XELement class but I am unable to understand how to pass element names dynamically in it.

XElement xmlout = new XElement("EmployeeRecords", list.Select(i => new XElement("Employee", i.Select(tag=>new XElement("Employee",tag)))));

I have also tried creating elements dynamically using XmlDocument but their also it is not working. Please guide regarding this as I am very new to XML file formats.

CodePudding user response:

What you are looking for is called XML Serialization. There is a good introduction to it available at: https://docs.microsoft.com/en-us/dotnet/standard/serialization/introducing-xml-serialization

CodePudding user response:

Here is the solution. Note that there is the 2nd parameter for Zip method, that allows you to implement more appropriate names for tuple fields names, instead of First and Second.

The code

using System.Xml.Linq;

string[][] data =
{
    new[] { "firstname", "lastname", "age", "empid" },
    new[] { "john", "maxwell", "31", "101" },
    new[] { "max", "lee", "45", "102" }
};

var xmlout = new XElement("EmployeeRecords",
    data.Skip(1).Select(_ => new XElement("Employee",
        // Zip joins two lists - names at data[0] and values, which are in _
        data[0].Zip(_).Select(_=>new XElement(_.First, _.Second))
    )))
    .ToString();

Console.Write(xmlout);

Output

<EmployeeRecords>
  <Employee>
    <firstname>john</firstname>
    <lastname>maxwell</lastname>
    <age>31</age>
    <empid>101</empid>
  </Employee>
  <Employee>
    <firstname>max</firstname>
    <lastname>lee</lastname>
    <age>45</age>
    <empid>102</empid>
  </Employee>
</EmployeeRecords>
  • Related