0

i am facing problem when read xml from url and want it to store in lables like that

XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("http://test.pragyaware.com/b2bwebservice.aspx?txnmessage=" + final);
lblname.Text = xmldoc.SelectSingleNode("/TXN/Name").FirstChild.Value;
lblacno.Text = xmldoc.SelectSingleNode("/TXN/AccountNo").FirstChild.Value;
lblkno.Text = xmldoc.SelectSingleNode("/TXN/KNumber").FirstChild.Value;
lbladdress.Text = xmldoc.SelectSingleNode("/TXN/Address").FirstChild.Value;
lblbillno.Text = xmldoc.SelectSingleNode("/TXN/BillNo").FirstChild.Value;
lblbilldt.Text = xmldoc.SelectSingleNode("/TXN/BillDate").FirstChild.Value;
lblduedt.Text = xmldoc.SelectSingleNode("/TXN/CashChequeDueDate").FirstChild.Value;
lblnetamt.Text = xmldoc.SelectSingleNode("/TXN/NetAmount").FirstChild.Value;
lblsurchrg.Text = xmldoc.SelectSingleNode("/TXN/Surcharge").FirstChild.Value;
lblgamt.Text = xmldoc.SelectSingleNode("/TXN/GrossAmount").FirstChild.Value;

if i am receiving values in all fields then everything is ok, but if i didnot received any one value from url in xml then its showing

System.NullReferenceException: Object reference not set to an instance of an object.

Please help me to get out from this. if i comment that lable which values is not received in xml then it runs ok

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
parveen
  • 11
  • 1
  • At least one of your XPath queries doesn't find a node, or at least one of them does not have a `FirstChild`. You cannot access members of a null object. – Crowcoder Nov 08 '15 at 18:22

1 Answers1

0
lblkno.Text = xmldoc.SelectSingleNode("/TXN/KNumber").FirstChild.Value;

This statement, like all the similar statements in your code, makes risky assumptions. It assumes that the /TXN/KNumber node exists, and it assumes that it has a child (FirstChild)

You said for yourself, there is a possibility that you don't receive some of the nodes. Therefore, you should not make those assumptions. Instead, have a method like the following, and change your statements to call that method. In this case, the label for which the xml node is not received will be empty.

lblname.Text = GetXmlNodeFirstChildValue(xmldoc, "/TXN/Name", string.Empty);

And the method:

private static string GetXmlNodeFirstChildValue(XmlDocument xmlDocument, string xPathQuery, string defaultValue)
{
    XmlNode xPathQueryResult = xmlDocument.SelectSingleNode(xPathQuery);
    if (xPathQueryResult != null)
    {
        XmlNode firstChild = xPathQueryResult.FirstChild;
        if (firstChild != null)
        {
            return firstChild.Value;
        }
    }
    return defaultValue;
}
Oguz Ozgul
  • 6,809
  • 1
  • 14
  • 26