C# 使用xmldocument读取xml

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18442917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:13:03  来源:igfitidea点击:

using xmldocument to read xml

c#xmldocument

提问by mribot

 <?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.

我正在尝试使用 c# 读取上面的 xml,但是我在 try catch 块中得到 null 异常,任何主体都可以建议所需的更改。

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

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

………………

采纳答案by Alex Filipovici

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

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

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

回答by Sergey Berezovskiy

You can use LINQ to XML to select all testcaseelements from your xml and parse them to TestCaseinstances:

您可以使用 LINQ to XMLtestcase从您的 xml 中选择所有元素并将它们解析为TestCase实例:

var xdoc = XDocument.Load("C:/Users/mkumar/Documents/testcase.xml");
var testCases = from tc in xdoc.Descendants("testcase")
                select new CommonLib.TestCase {
                   date = (string)tc.Element("date"),
                   name = (string)tc.Element("name"),
                   sub= (string)tc.Element("subject")
                };

BTW you have only one testcaseelement currently, which is root of XML file. So, you can do instead:

顺便说一句,您目前只有一个testcase元素,即 XML 文件的根。所以,你可以这样做:

var tc = XElement.Load("C:/Users/mkumar/Documents/testcase.xml");
var testCase = new CommonLib.TestCase {
                   date = (string)tc.Element("date"),
                   name = (string)tc.Element("name"),
                   sub= (string)tc.Element("subject")
                };

回答by Bassam Alugili

private static void Main(string[] args)
{
  XmlDocument xd = new XmlDocument();
  xd.Load("C:\test1.xml");

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

  foreach (XmlNode node in nodelist) // for each <testcase> node
  {
    try
    {
      var name = node.SelectSingleNode("date").InnerText;
      var date = node.Attributes.GetNamedItem("name").Value;
      var sub = node.Attributes.GetNamedItem("subject").Value;

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


    }
  }

This will work I have test it @Alex correct answer

这会起作用我已经测试过了@Alex正确答案

回答by Ehsan

You are trying to read attributes whereas date, nameand subjectare not attributes. They are subnodes.

您正在尝试读取,而属性date, namesubject没有属性。它们是子节点。

your code should be like this

你的代码应该是这样的

XmlDocument xd = new XmlDocument();
xd.Load("test.xml");
XmlNodeList nodelist = xd.SelectNodes("/testcase"); // get all <testcase> nodes

foreach (XmlNode node in nodelist) // for each <testcase> node
{
    try
    {                    
          string name = node.SelectSingleNode("name").InnerText;
          string date = node.SelectSingleNode("date").InnerText;
          string sub = node.SelectSingleNode("subject").InnerText;
    }
    catch (Exception ex)
    {
          MessageBox.Show("Error in reading XML", "xmlError", MessageBoxButtons.OK);
    }
}

回答by Georgy Vandyshev

Your Xml do not contain Attributes. date, name and subject - it's Child Nodes of the testcase Node. Try this:

您的 Xml 不包含属性。日期、名称和主题 - 它是测试用例节点的子节点。尝试这个:

...
tc.name = node["name"].InnerText;
...

or this:

或这个:

...
tc.name = node.SelectSingleNode("name").InnerText;
...