首页 > 解决方案 > 使用 C# 读取 XML 文件属性和元素

问题描述

我的 XML 文件如下所示:

<device name="dev. 1" nodes="16" scenarios="20">
  <package>Pack. 1</package>
  <info>info...</info>
  <picture>pic</picture>
  <nodes>
    <node no="1" name="OUT_1" type="source"/>
    <node no="2" name="OUT_2" type="source"/>
    <node no="3" name="OUT_3" type="source"/>
    <node no="4" name="OUT_4" type="source"/>
  </nodes>
  <scenario name="scenario 1">
    <zth m_node="1" d_node="1" model="table" points="190">
      <data time="1" value="0.1"/>
      <data time="2" value="2"/>
      <data time="2" value="4"/>
    </zth>
    <zth m_node="1" d_node="2" model="table" points="190">
      <data time="1" value="0.3"/>
      <data time="2" value="4"/>
    </zth>
  </scenario>
  <scenario name="scenario 2">
    <zth m_node="1" d_node="1" model="table" points="190">
      <data time="2" value="2"/>
      <data time="1" value="0.3"/>
      <data time="2" value="4"/>
    </zth>
    <zth m_node="1" d_node="2" model="table" points="190">
      <data time="1" value="0.3"/>
      <data time="2" value="4"/>
    </zth>
  </scenario>
</device>

我需要读取的数据是:来自 Element scen 的属性<data>名称d_node="2"<zth>.

这是我尝试过的:

    public class Scenario {
        public string name { get; set; }
        public List<string> ZthList { get; set; }
    }

    public class Zth {
        public string m_node { get; set; }
        public string d_node { get; set; }
        public string time { get; set; }
        public string value { get; set; }
    }
    public class XMLReader
    {

        public void xmlReader()
        {

            string currentDir = Environment.CurrentDirectory;
            //getting the directory
            DirectoryInfo directory = new DirectoryInfo(
            Path.GetFullPath(Path.Combine(currentDir, @"..\..\" + @"utils\XML\XMLFile1.xml")));

            XDocument doc = XDocument.Load(Path.Combine(currentDir, @"..\..\" + @"utils\XML\XMLFile1.xml"));
            var scenarios = (from s in doc.Root.Elements("scenario")
                             select new Scenario{
                                 name = (string)s.Attribute("name"), 
                                 ZthList = s.Elements("zth")
                                            .Select(r => new Zth
                                            {
                                                m_node = (string)r.Attribute("m_node"),
                                                d_node = (string)r.Attribute("d_node"),
                                                time = (string)r.Element("data").Attribute("time"),
                                                value = (string)r.Element("data").Attribute("value"),
                                            }).ToList()
                             }).ToList();
            var zth_d_node = scenarios.Where(x => x.ZthList.Any(r => r.d_node == "1")).ToList();
            var s_names = scenarios.Where(x => x.Element("").Value.Equals("name")).toList();

            Console.WriteLine("List: ");
            Console.WriteLine(String.Join(", ", scenarios));
        }
    }

我得到和错误:Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type 'System.Collections.Generic.List<project1.utils.Zth>' to 'System.Collections.Generic.List<string>'

来自timeand的数据value也是 double 类型,我将其更改为字符串,因为我遇到了类似的错误,但仍然无法正常工作

标签: c#xml

解决方案


我做了很多改变。我总是建议避免使用“var”,除非有必要。你完全糊涂了,因为你不知道变量类型。:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication16
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XMLReader xReader = new XMLReader();
            xReader.xmlReader(FILENAME);
        }
 
    }
    public class Scenario
    {
        public string name { get; set; }
        public List<Zth> ZthList { get; set; }
    }

    public class Zth
    {
        public string m_node { get; set; }
        public string d_node { get; set; }
        public string time { get; set; }
        public string value { get; set; }
    }
    public class XMLReader
    {

        public void xmlReader(string filename)
        {


            XDocument doc = XDocument.Load(filename);
            List<Scenario> scenarios = (from s in doc.Root.Elements("scenario")
                             select new Scenario
                             {
                                 name = (string)s.Attribute("name"),
                                 ZthList = s.Elements("zth")
                                            .Select(r => new Zth()
                                            {
                                                m_node = (string)r.Attribute("m_node"),
                                                d_node = (string)r.Attribute("d_node"),
                                                time = (string)r.Element("data").Attribute("time"),
                                                value = (string)r.Element("data").Attribute("value")
                                            }).ToList()
                             }).ToList();
            List<Scenario> zth_d_node = scenarios.Where(x => x.ZthList.Any(r => r.d_node == "1")).ToList();
            List<Scenario> s_names = scenarios.Where(x => x.name == "name").ToList();

            Console.WriteLine("List: ");
            Console.WriteLine(String.Join(", ", scenarios.Select(x => x.name )));
        }
    }
}

在此处输入图像描述


推荐阅读