1

I am receiving a XML strings from and API, and would like to convert these to C# objects key-value in order to handle these values also apply some asserts.

The messages are of the form string format:

<?xml version="1.0" encoding="UTF-8"?>
<ReportData>
   <ProjectName>Test Data</ProjectName>
   <Unit>Unit 1</Unit>
   <ReportLabel.Cost>394</ReportLabel.Cost>
</ReportData>

After i get the string API response i am trying to deserialize the XMl like this where responseAPI is the xml above:

XmlDocument doc = new XmlDocument();

            using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(responseAPI), XmlDictionaryReaderQuotas.Max))
            {
                XElement xml = XElement.Load(reader);
                doc.LoadXml(xml.ToString());
            }

At this point i have and xml but i can not get a key-value object.

i am trying

var jsonText = JsonConvert.SerializeXmlNode(doc);

or

serializer = new XmlSerializer(typeof(Object));
using (TextReader reader = new StringReader(responseAPI))
{
  var result = (Object)serializer.Deserialize(reader);
}

or

var response = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseAPI);

I am new to with this kind of response in XML and am not sure the way to performing this. It is not as easy as JSON format.

Andres
  • 29
  • 3

2 Answers2

1

You can use System.Xml.Linq for this task.
Here is one way to create a dictionary from the XML:

static void Main(string[] args)
{
    // or use other overload of the Load() method if the XML is not comes from a file stream, uri etc...
    var xmldoc = System.Xml.Linq.XDocument.Load("YOUR FILE PATH");

    Dictionary<string, string> XMLKeyval = new Dictionary<string, string>();
    foreach (var name in xmldoc.Descendants("ReportData").Elements()
                        .Select(x => new { Name = x.Name, Value = x.Value }).Distinct())
    {
        XMLKeyval.Add(name.Name.LocalName, name.Value);
    }

    // Output
    foreach (KeyValuePair<string, string> itm in XMLKeyval)
    {
        Console.WriteLine(itm.Key + ": " + itm.Value);
    }

    Console.ReadLine();
}
Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52
0

You can not directly convert xml to a dict of key value pair, Instead we need to iterate through each node in xml and add it as a key value pair to a dict object.

please refer Converting an XML-document to a dictionary

Mahesh Anakali
  • 344
  • 1
  • 8