user1416156
user1416156

Reputation: 3023

How to read a node in an xml in this format

I have an getting an xml response on this format

  <?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n
       <PlatformResponse xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://platform.intuit.com/api/v1\">\r\n  
<ErrorMessage>OAuth Token rejected</ErrorMessage>\r\n  
<ErrorCode>270</ErrorCode>\r\n  
<ServerTime>2012-06-19T00:01:31.5150146Z</ServerTime>\r\n
</PlatformResponse>

I need to grab the value in the <ErrorCode> node, for that I did the following but it is not getting any values..

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(xmlResponse);

            XmlNodeList xnList = xml.SelectNodes("PlatformResponse");
            foreach (XmlNode xn in xnList)
            {
                result.Message = xn["ErrorCode"].InnerText;
            }

Any help would be much appreciated.

Upvotes: 1

Views: 183

Answers (3)

For this, since the attribute is on the main document element itself, you can simply do

    XmlDocument xml = new XmlDocument();
    xml.LoadXml(xmlText);
    result.Message = xml.DocumentElement["ErrorCode"].InnerText

Upvotes: 0

AvkashChauhan
AvkashChauhan

Reputation: 20571

I just tested the code and it does work fine:

        XmlDocument xml = new XmlDocument();
        XmlTextReader reader = new XmlTextReader("Path_to_your_xml");
        xml.Load(reader);
        XmlNodeList xnList = xml.SelectNodes("PlatformResponse");
        foreach (XmlNode xn in xnList)
        {
            MessageBox.Show(xn["ErrorCode"].InnerText);
        }

Upvotes: 0

Orn Kristjansson
Orn Kristjansson

Reputation: 3485

There seems to be some dirt in your PlatformResponse node that's giving problems, ( xmlns:xsd= etc... )

Using this xml

String sXml = @"<?xml version='1.0' encoding='utf-8'?>
   <PlatformResponse >
        <ErrorMessage>OAuth Token rejected</ErrorMessage>
        <ErrorCode>270</ErrorCode>
        <ServerTime>2012-06-19T00:01:31.5150146Z</ServerTime>
    </PlatformResponse>";

And select like

XmlNodeList xnList = xml.SelectNodes("/PlatformResponse");

Your code works fine.

Upvotes: 1

Related Questions