Damage
Damage

Reputation: 29

C# Parse XML Response to Array

I'm working with a third party system that returns the following xml response

{<origenxml type="data">
<data>
<item>
<id><![CDATA[PIN/4590/67]]></id>
<filename><![CDATA[CS.STAR]]></filename>
<group>
<id>MAIN</id>
<dictionary id="CS.ST.BOXNO">
<desc><![CDATA[boxes]]></desc>
<value ln="0"></value>
<raw-value ln="0"></raw-value>
<value ln="1"><![CDATA[121880 ]]></value>
<raw-value ln="1"><![CDATA[B-FILE394**BCBF*BC*121880*]]></raw-value>
<value ln="2"><![CDATA[121881 ]]></value>
<raw-value ln="2"><![CDATA[B-FILE394**BCBF*BC*121881*]]></raw-value>
<value ln="3"><![CDATA[121882 ]]></value>
<raw-value ln="3"><![CDATA[B-FILE394**BCBF*BC*121882*]]></raw-value>
<value ln="4"><![CDATA[940288 ]]></value>
<raw-value ln="4"><![CDATA[B-FILE80**BCBF*BC*940288*]]></raw-value>
<value ln="5"><![CDATA[170415 ]]></value>
<raw-value ln="5"><![CDATA[ALPHA**BC*BC*170415*]]></raw-value>
</raw-value>
</dictionary>
</group>
</item>
</data>
</origenxml>}

Each line under Boxes, represents an object where the value is the Id and the raw-value is the data ( so line 5 - ID = 170415 and the Value = ALPHA**BC*BC*170415*) but i really can't figure out the best way to parse the xml. I have no control over the response xml, so i can't anything helpful like extra node names

Upvotes: 0

Views: 364

Answers (1)

Anthony T.
Anthony T.

Reputation: 268

First thing, I want to make sure this is really the XML, because it's malformed. There's a floating end tag for the </raw-value> right before the </dictionary>. Assuming that is a mistake then the solution is easy with Linq over XML.

You'll need to add the following using statements:

using System.IO;
using System.Xml.Linq;

I created this sample in a Console application, but you should be able to easily adapt it. The first step is to create an XDocument object from your XML. I'm pulling the text from a constant string value.

static XDocument CreateDocument()
{
    using (var reader = new StringReader(testData)) {
        return XDocument.Load(reader);
    }
}

The rest is simply to create a query and enumerate it.

var doc = CreateDocument();

var results = from value in doc.Descendants("value")
                join rawValue in doc.Descendants("raw-value")
                on value.Attribute("ln").Value equals rawValue.Attribute("ln").Value
                select new { Value = value.Attribute("ln").Value, RawValue = rawValue.Value };

foreach (var result in results) {
    Console.WriteLine($"{result.Value} => {result.RawValue}");
}

Upvotes: 1

Related Questions