-1

in this xml

<Roots>
   <Root Name="cab">element_list</Root>
</Roots>

I want to get the value of attribute Name which is cab and element_list

I have this code

XmlDocument doc = new XmlDocument();
doc.LoadXml("<Root Name=\"cab\">element_list</Root>");
XmlElement root = doc.DocumentElement;
var values = doc.Descendants("Roots").Select(x => new { Name = (string)x.Attribute("Name"), List = (string)x }).ToList(); 

What I get when I run the debugger is

values>  Name = "null",  List = "element_list"

I am not understanding why I am getting a null value when I should be getting cab for the attribute Name

Sean Davis
  • 23
  • 1
  • 6

1 Answers1

0

XDocument is much easier to work with compared to XmlDocument. Perhaps consider switching to it?

    public static void ParseXml()
    {
        string str = "<Roots><Root Name=\"cab\">element_list</Root></Roots>";

        using TextReader textReader = new StringReader(str);
        XDocument doc = XDocument.Load(textReader);

        var val = doc.Element("Roots").Element("Root").Attribute("Name").Value;

    }
R J
  • 495
  • 5
  • 12