-2

I am trying to get XML values from the following XML node:

<StockQuotes>
  <Stock>
    <Symbol>LLOY.L</Symbol>
    <Last>76.27</Last>
    <Date>8/29/2014</Date>
  </Stock>
</StockQuotes>

Here is my code:

XmlDocument quoteXML = new XmlDocument();

string strData = myXMLfile;
quoteXML.LoadXml(strData);
XmlNode nodes = quoteXML.SelectSingleNode("StockQuotes/Stock/Last/Date");
string strPrice = nodes["Last"].InnerText;
string strDate = nodes["Date"].InnerText;

Response.Write( strPrice + strDate );

I am getting the error:

Object reference not set to an instance of an object. 

when I write the whole string strData to the view I get all of the XML so I know the file is valid.

user3746002
  • 43
  • 1
  • 3
  • 8

2 Answers2

0

SOURCE OF THE PROBLEM:

quoteXML.SelectSingleNode("StockQuotes/Stock/Last/Date"); SelectSingleNode call will return representation of <Date>8/29/2014</Date>,

But you try to access subnodes ["Last"] and ["Date"], that are not child nodes of <Date>8/29/2014</Date> and taking into account that indexer returns:

The first XmlElement that matches the specified name. It returns a null reference (Nothing in Visual Basic) if there is no match.

nodes["Last"] and nodes["Base"] will be both null, resulting in NullReferenceException on .InnerText property access.

SOLUTION:

Use

XmlNode nodes = quoteXML.SelectSingleNode("StockQuotes/Stock");

to access Stock node instead.

Community
  • 1
  • 1
Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53
0

The issue was with special charchters in the XML feed. I have resolved the issue and used:

'string strData = WebService.GetDate(); // returns xml as string
            string decoded = WebUtility.HtmlDecode(strData); quoteXML.LoadXml(decoded); 

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(decoded);
            XmlNodeList xnList = xml.SelectNodes("/StockQuotes/Stock");
            foreach (XmlNode xn in xnList)
            {
                strQuote = xn["Last"].InnerText;
            }'
user3746002
  • 43
  • 1
  • 3
  • 8