How to Read XML in .NET?

XML noob here! So I have some xml data:

<DataChunk>
    <ResponseChunk>
        <errors>
            <error code=\"0\">
                Something happened here: Line 1, position 1.
            </error>
        </errors>
    </ResponseChunk>
</DataChunk>

How would I get the a list of "errors" where I can get access to the "error code" and the text description following...? Also, I'm using .net4.0 in c#...thanks!


Solution 1:

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.

Solution 2:

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.

Solution 3:

XmlReader xmlReader = XmlReader.Create(new StringReader(response));
        AmortizationCalculatorBE amortization = new AmortizationCalculatorBE();
List<PaymentCalculator> paymentList = new List<PaymentCalculator>();
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(new StringReader(response));
        XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("response/amortizationschedule/payment");
        XmlNodeList nodeList2 = xmlDoc.DocumentElement.SelectNodes("response");
        foreach (XmlNode node in nodeList)
        {
            PaymentCalculator payment = new PaymentCalculator();
            payment.beginningbalance = node.SelectSingleNode("beginningbalance").InnerText;
            payment.principal = node.SelectSingleNode("principal").InnerText;
            payment.interest = node.SelectSingleNode("interest").InnerText;
            paymentList.Add(payment);

        }
        amortization._PaymentCalculator = paymentList;
        foreach (XmlNode node in nodeList2)
        {
            amortization.totalprincipal = node.SelectSingleNode("totalprincipal").InnerText;
            amortization.totalinterest = node.SelectSingleNode("totalinterest").InnerText;

        }