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".
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["succes"].Value;
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);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
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();
}
}
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.)
var at =
XElement.Parse("<reply success=\"true\">More nodes go </reply>").Attribute("success");
if (at != null) Console.Write(at.Value);