Search code examples
c#xmlxmldocument

Selectnodes only get the first node


I have an XML file looking like this:

<data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<Alert>warning</Alert>
<Alert2>warning</Alert2>
</row>
</data>

When I use the code below I only get the "Alert"-node. But I wan't "Alert2" as well (and so on...). What am I missing here?

using (XmlReader reader = cmd.ExecuteXmlReader())
            {
                string xmlFile = "";
                while (reader.Read())
                {
                    xmlFile = reader.ReadOuterXml();
                }

                var doc = new XmlDocument();
                doc.LoadXml(xmlFile);
                var nodes = doc.SelectNodes("data/row");

                if (nodes == null) return columns;
                var i = 0;
                foreach (XmlNode node in nodes)
                {
                    var column = node.ChildNodes[i].Name;
                    columns.Add(column);
                    i++;
                }
                return columns;
            }

Solution

  • Change your loop to the equivalent of:

        var doc = new XmlDocument();
        doc.LoadXml(xml);
        var nodes = doc.SelectNodes("data/row");
    
        int i = 0;
        foreach (XmlNode node in nodes)
        {
            foreach (var child in node.ChildNodes)
            {
                var element = (XmlElement)child;
                string nodeName = element.Name;
                string value = element.InnerXml;
                i++;
            }
    
        }