-2

I have the following XML:

<Root><Node1>node1 value</Node1><Node2>node2 value</Node2></Root>

I'd like to check if Root is the first node. If so, I then want to get the values for the to child nodes.

This XML is inside of an XElement. I've tried this:

xml.Element("Root")

but that returns null. If Root exist, shouldn't it return a non null value?

4thSpace
  • 43,672
  • 97
  • 296
  • 475

3 Answers3

0
        string xml = @"<Root><Node1>node1 value</Node1><Node2>node2 value</Node2></Root>";

        XDocument doc = XDocument.Parse(xml);

        var root = doc.Root;
        if(root.Name == "Root")
        {
            foreach(var el in root.Descendants())
            {
               string nodeValue = el.Value;
            }

        }

You can check the name of the Root element from Root.Name. After that loop all elements in the root using doc.Root.Descendants().

mybirthname
  • 17,949
  • 3
  • 31
  • 55
0

Since xml is an instance of XElement, it already references the root element, which in this case named Root. Doing xml.Element("Root") will return result only if the <Root> element has another child <Root>.

I'd like to check if Root is the first node.

You can simply check the Name of the root element :

var raw = "<Root><Node1>node1 value</Node1><Node2>node2 value</Node2></Root>";
var xml = XElement.Parse(raw);
if (xml.Name.ToString() == "Root")
    Console.WriteLine("Success");
else 
    Console.WriteLine("Fail");
har07
  • 88,338
  • 12
  • 84
  • 137
0

Try this solution

XDocument doc = XDocument.Parse(@"<Root><Node1>node1value</Node1><Node2>node2value</Node2></Root>");
        if(doc!=null)
        {
            if (doc.Root.Name.LocalName == "Root")
            {
                foreach (var i in doc.Descendants())
                   Console.WriteLine(i.Value);
            }
        }
Krishna_K_Batham
  • 310
  • 1
  • 4
  • 10