Search code examples
c#xmlxml-parsingxmlreader

XML parsing in C#. Issue with Descendants


I have an XML string that needs parsing.

Code looks as below:

inputXML = "<elementList xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
            <NodePrime>
                <Node>
                     <NodeA>1</NodeA>
                     <NodeB>2</NodeB>
                </Node>
                <Node>
                     <NodeA>3</NodeA>
                     <NodeB>4</NodeB>
                </Node>
             </NodePrime>
             </elementList>";

var ItemList = new List<ItemList>();
using(XmlReader Reader = XmlReader.Create(new StringReader(inputXML)))
{
     Reader.read();
     var doc = XDocument.Load(Reader);
     var xmlnode = doc.Descendants("Node");
     foreach(var item in xmlHeirarchy)
     {
         var ListA = new ItemList
         {
             itemA = item.Element("NodeA").Value;
             itemB = item.Element("NodeB").Value;
         };
         ItemList.Add(ListA );
     }
}

My issue is with the doc.Descendants as my xmlnode returns empty.

Please let me know what is it that I am doing wrong and the best way to do it.


Solution

  • You can use XDocument.Parse() to populate XDocument from string, which is simpler than your current approach. Then doc.Descendants("Node") should've worked as demonstrated below :

    var inputXML = @"<elementList xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
        <NodePrime>
            <Node>
                 <NodeA>1</NodeA>
                 <NodeB>2</NodeB>
            </Node>
            <Node>
                 <NodeA>3</NodeA>
                 <NodeB>4</NodeB>
            </Node>
         </NodePrime>
         </elementList>";
    
    var ItemList = new List<ItemList>();
    var doc = XDocument.Parse(inputXML);
    var xmlnode = doc.Descendants("Node");
    foreach(var item in xmlnode)
    {
        var ListA = new ItemList
        {
            itemA = item.Element("NodeA").Value,
            itemB = item.Element("NodeB").Value
        };
        ItemList.Add(ListA );
    }
    Console.WriteLine(ItemList.Count());
    

    dotnetfiddle demo

    output :

    2