0

I get this XML string for my web page, how can I retrieve data from that XML and assign values to labels in my web page?

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<things>
    <bat>201400000586</bat>
    <status>Y</status>
    <totalAmount>3090</totalAmount>
    <billno>P2355</billno>
    <ReceiveDate>27/04/2015 06:22:18 PM</ReceiveDate>
</things>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
trm nhcl
  • 17
  • 4
  • You will need to parse the XML. I am not sure why you have put C# tag to this question. But if you want to do it in C# you can use XMLReader. – usamazf Apr 01 '16 at 06:45
  • Interesting that this is marked as "exact duplicate." Between the "duplicate" and this answer are 5 different solutions to the same problem. That is why I started my answer with "There are different ways to do this." – smoore4 Apr 02 '16 at 11:03

2 Answers2

0

Firstly load the Xml Doc using XMLDocument

  XDocument doc = XDocument.Load(filePath);
  XElement rootElm = doc.Element("things")

Now using linq you can fetch IENumerable

IEnumerable<XElement> childList = from Y in rootElm.Root.Elements()
                                                  select Y;

Now ou can loop through list items

 foreach (XElement elm in childList)
  {
   //Here you can access elements this way
   Console.log(elm.Element("status").Value);
    ..........
  }

Here you can even edit the contents in xml file and save them. Assign the values for the XElement type elements in the loop

doc.Save(filePath);
bhanu.cs
  • 1,345
  • 1
  • 11
  • 25
0

There are different ways to do this. Here is one.

You'll need to add "using System.Xml.XPath;"

        XPathDocument doc = new XPathDocument(Server.MapPath("~/XMLFile1.xml"));

        XPathNavigator nav = doc.CreateNavigator();

        XPathExpression exp = nav.Compile(@"/things");

        foreach (XPathNavigator item in nav.Select(exp))
        {

            label1.Text = item.SelectSingleNode("bat").ToString();
            label2.Text = item.SelectSingleNode("totalAmount").ToString();

        }

Or you can load it as a string, then use EITHER XmlElement or XmlNode with such a simple XML structure.

        XmlDocument m_xml = new XmlDocument();
        m_xml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes"" ?><things><bat>201400000586</bat><status>Y</status><totalAmount>3090</totalAmount><billno>P2355</billno><ReceiveDate>27/04/2015 06:22:18 PM</ReceiveDate></things>");

        XmlNode node_bat = m_xml.SelectSingleNode("//things/bat");
        XmlNode node_totalAmount = m_xml.SelectSingleNode("//things/totalAmount");

        XmlElement node_bat1 = m_xml.DocumentElement["bat"];
        XmlElement node_totalAmount1 = m_xml.DocumentElement["totalAmount"];

        label1.Text = node_bat1.InnerText;
        label2.Text = node_totalAmount1.InnerText;
smoore4
  • 4,520
  • 3
  • 36
  • 55