Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using xmldocument to read xml

Tags:

c#

xmldocument

 <?xml version="1.0" encoding="utf-8" ?> 

  <testcase>
      <date>4/12/13</date>
      <name>Mrinal</name>
      <subject>xmlTest</subject>
  </testcase>

I am trying to read the above xml using c#, But i get null exception in the try catch block can any body suggest the required change.

static void Main(string[] args)
        {        

            XmlDocument xd = new XmlDocument();
            xd.Load("C:/Users/mkumar/Documents/testcase.xml");

            XmlNodeList nodelist = xd.SelectNodes("/testcase"); // get all <testcase> nodes

            foreach (XmlNode node in nodelist) // for each <testcase> node
            {
                CommonLib.TestCase tc = new CommonLib.TestCase();

                try
                {
                    tc.name = node.Attributes.GetNamedItem("date").Value;
                    tc.date = node.Attributes.GetNamedItem("name").Value;
                    tc.sub = node.Attributes.GetNamedItem("subject").Value;

                 }
                catch (Exception e)
                {
                    MessageBox.Show("Error in reading XML", "xmlError", MessageBoxButtons.OK);
                }

........ .....

like image 404
mribot Avatar asked Dec 12 '22 11:12

mribot


1 Answers

The testcase element has no attributes. You should be looking to it's child nodes:

tc.name = node.SelectSingleNode("name").InnerText;
tc.date = node.SelectSingleNode("date").InnerText;
tc.sub = node.SelectSingleNode("subject").InnerText;

You might process all nodes like this:

var testCases = nodelist
    .Cast<XmlNode>()
    .Select(x => new CommonLib.TestCase()
    {
        name = x.SelectSingleNode("name").InnerText,
        date = x.SelectSingleNode("date").InnerText,
        sub = x.SelectSingleNode("subject").InnerText
    })
    .ToList();
like image 97
Alex Filipovici Avatar answered Dec 24 '22 21:12

Alex Filipovici