Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

c# - using xmldocument to read xml

 <?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);
                }

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...