简体   繁体   中英

Getting attribute value of an XML Document using C#

Suppose I have the following XML Document.

<reply success="true">More nodes go here</reply>

How to get the value of the attribute success, which in this case would be the string "true".

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();
        }
    }
var at = 
XElement.Parse("<reply success=\"true\">More nodes go  </reply>").Attribute("success");
if (at != null) Console.Write(at.Value);

The following code works for me.

String strXML = "<reply success=\"true\">More nodes go here</reply>";

    using (XmlReader reader = XmlReader.Create(new StringReader(strXML)))
    {
            reader.ReadToFollowing("reply");
            reader.MoveToContent();
            string strValue = reader.GetAttribute("success");
            Console.WriteLine(strValue);
    }

If attribute value returns null or empty, try this.

     string x="<node1 id='12345'><node2 Name='John'></node2><node3 name='abc'></node3></node1>";
        XmlDocument xml = new XmlDocument();
        xml.LoadXml(x);
        var node = xml.GetElementsByTagName("node3");
        xml = new XmlDocument();
        xml.LoadXml(nodes[0].OuterXml);
        XmlElement root = xml.DocumentElement;
        String requiredValue = root.GetAttribute("name");  
    returns "abc";      

Here's an alternative solution using XmlReader which may be a little more efficient than using XmlDoument although that's proably negligible on such a small XML document

string input = "<reply success=\"true\">More nodes go here</reply>";

using (XmlReader xmlReader = XmlReader.Create(new StringReader(input)))
{
    xmlReader.MoveToContent();
    string success = xmlReader.GetAttribute("success");
    Console.WriteLine(success);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM