使用xmldocument读取xml [英] using xmldocument to read xml

查看:75
本文介绍了使用xmldocument读取xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我正在尝试使用c#读取上述xml,但是我在try catch块中得到了null异常,任何机构都可以提出所需的更改.

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

.........

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

推荐答案

testcase 元素没有属性.您应该查看它的子节点:

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

这篇关于使用xmldocument读取xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆