Getting attribute value of an XML Document using C#

I would try something like this:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<reply success=\"true\">More nodes go here</reply>");

XmlElement root = doc.DocumentElement;

string s = root.Attributes["success"].Value;

If you load the XML into an XmlDocument, there are any number of ways to get the attribute's value. You could use XPath to find the attribute:

XmlAttribute a = doc.SelectSingleNode("/reply/@success");
Console.Write(a.Value);

If you already have the XmlElement that the attribute appears on (which in this case is the document element), then you can just use GetAttribute:

Console.Write(doc.DocumentElement.GetAttribute("success"));

There are similar approaches if you're using XPathDocument or XmlReader or XDocument.

In all cases, though, you want to be getting the attribute by its name, not its position. In your test case there's only one attribute; in any real-world application multiple attributes are likely, and attribute ordering in XML is not significant. These two elements are semantically equivalent:

<a foo='true' bar='false'/>

<a bar='false' foo='true'/>

You don't even know that the XML parser will present attributes to you in the same order they appear in the document; depending on the implementation, the parser may give them to you in alphabetical order, or in random order. (I've seen both.)


    using System;
    using System.Linq;
    using System.Xml.Linq;

    class MyClass
    {
        static void Main(string[] args)
        {
            XElement xmlcode =
            XElement.Parse("<reply success=\"true\">More nodes go  </reply>");

            var successAttributes =
                from attribute in xmlcode.Attributes()
                where attribute.Name.LocalName=="success" 
                select attribute ;

            if(successAttributes.Count()>0)
            foreach (var sa in successAttributes)
            {
                Console.WriteLine(sa.Value);           
            }
            Console.ReadLine();
        }
    }

Tags:

C#

Xml