Home > other >  Convert xml into array in c#
Convert xml into array in c#

Time:05-14

I have a XML file which I want to convert into an array. I have tried using Xmlserialzer class and it's working but for some reasons I am not allowed to use it in my project. I have looked at few solutions but none of them match the requirement I have. Please guide me regarding this. Below is the sample XML file.

<?xml version="1.0" encoding="UTF-8"?>
    <Configuration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <PatientRecord>
        <Patient>
            <FirstName>John</FirstName>
            <LastName>Smith</LastName>
            <Age>46</Age>
        </Patient>
        <Patient>
            <FirstName>Martha</FirstName>
            <LastName>Stewart</LastName>
            <Age>51</Age>
        </Patient>
    </PatientRecord>

array must be like:

{"Firstname", "LastName", "Age"}
{"John","Smith","46"}
{"Martha", "Stewart", "51"}

What I have tried:

XmlReader xmlFile;
xmlFile = XmlReader.Create(inputPath, new XmlReaderSettings());
System.Data.DataSet ds = new System.Data.DataSet();
ds.ReadXml(xmlFile);
int row_count = ds.Tables[0].Rows.Count;
int col_count = ds.Tables[0].Columns.Count;
string[,] data = new string[row_count, col_count];
for(int i = 0; i < row_count; i  )
{
    for(int j = 0; j < row_count 1; j  )
    {
        data[i, j] = ds.Tables[0].Rows[i][j].ToString();
        data[i, j] = ds.Tables[0].Rows[i][j].ToString();
        data[i, j] = ds.Tables[0].Rows[i][j].ToString();
    }                
}

I have tried creating a 2-d array which is getting values but not tags.

CodePudding user response:

I assume that there is also a closing element for Configuration so, your xml is valid.

This is how you can use DataTable to get the desired output

Collect the information about columns

DataTable dt = ds.Tables[1];
var columns = new List<string>();
foreach (DataColumn dc in dt.Columns)
{
    if (dc.ColumnMapping == MappingType.Hidden) continue;
    columns.Add(dc.ColumnName);
}
  • Tables[0] does not contain too much valuable information
    • On the other hand Tables[1] does
  • The if statement makes sure that you skip the PatientRecord_Id dynamically generated column
  • You can call ToArray on the columns if you really need as an array.

Collect the information for rows

var rows = new List<List<string>>();
foreach (DataRow dr in dt.Rows)
{
    var row = new List<string>();
    foreach (DataColumn dc in dt.Columns)
    {
        if (dc.ColumnMapping == MappingType.Hidden) continue;
        row.Add(dr[dc].ToString());
    }
    rows.Add(row);
}
  • Here you can't use the dr.ItemArray for the inner loop
    • With that you could not ignore the generated column's value

Disclaimer: I've used List<string> and List<List<string>> in order to focus my post about the DataTable API usage.

  • Related