Skip to content

Process Nested XML using C#

Recently I was helping a friend with a bit tricky piece of code. The task was to process and XML that didn’t have namespace and has nested child items with similar names.

<xml>
<root>
<node>
<node>value 1</node>
<node>vallue 2</node>
</node>
<node>
<node>value 1</node>
<node>vallue 2</node>
</node>
</root>
</xml>

  Actual XML was far more complex with a lot of CDATA section and other details. After spending sometime around I had to come up with a way to load this XML into dataset for further processing. As there were no namespace or any other element to identify XML node here is what I came up with at first

 

public static DataSet GetDatSet(XmlNodeList nodeList)
        {
            DataSet dataSet = new DataSet();
            XmlReader reader;

            for (int i = 0; i < nodeList.Count; i++)
            {
                reader = new XmlTextReader(nodeList.Item(i).OuterXml, XmlNodeType.Element, new XmlParserContext(null, null, null, XmlSpace.None));
                dataSet.ReadXml(reader);
            }
            return dataSet;
        }

  but later on due to some other conditions I had to devise another mechanism and finally I settled with some Xpath expressions.

Leave a Reply

Your email address will not be published. Required fields are marked *