How to Read XML in .NET?

You can use Linq to XML:

var doc = XDocument.Parse(xml);
var errors = from e in doc.Descendants("error")
             select new
             {
                code = e.Attribute("code").Value,
                msg = e.Value.Trim()
             };

foreach (var e in errors)
{
    // use e.code & e.msg
}

If your input XML is very large however, it might be better to go through the document with an XMLReader.


Load the XML into an XmlDocument and then use xpath queries to extract the data you need.

For example

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstring);

XmlNode errorNode = doc.DocumentElement.SelectSingleNode("/DataChunk/ResponseChunk/Errors/error");

string errorCode = errorNode.Attributes["code"].Value;
string errorMessage = errorNode.InnerText;

If there is potential for the XML having multiple error elements you can use SelectNodes to get an XmlNodeList that contains all elements at that xpath. For example:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstring);

XmlNodeList errorNodes = doc.DocumentElement.SelectNodes("/DataChunk/ResponseChunk/Errors/error");

foreach(XmlNode errorNode in errorNodes)
{
  string errorCode = errorNode.Attributes["code"].Value;
  string errorMessage = errorNode.InnerText;
}

Option 2

If you have a XML schema for the XML you could bind the schema to a class (using the .NET xsd.exe tool). Once you have that you can deserialise the XML into an object and work with it from that object rather than the raw XML. This is an entire subject in itself so if you do have the schema it is worth looking into.

Tags:

C#

Xml