How to Read XML in .NET?

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.

Leave a Comment