如何使用XML ID来填充类对象?(How to use xml id to fill class

2019-11-05 10:29发布

我在C#以下的类定义:

class Supervisor
{
    public string Id { set; get; }
    public string Name { set; get; }
    public int Contracts { set; get; }
    public long Volume { set; get; }
    public int Average { get; }
}

我也有这个XML文档:

 <digital-sales xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <supervisor id="1236674">
        <Name>Hiroki</Name>
        <Contract>11</Contract>
        <Volume>1036253</Volume>
        <Average>94205</Average>
    </supervisor>
    <supervisor id="123459">
        <Name>Ayumi</Name>
        <Contract>5</Contract>
        <Volume>626038</Volume>
        <Average>125208</Average>
    </supervisor> ...
 </digital-sales>

在这个主我为每个监督员创建对象,并通过搜索ID填写其数据。 不过我总是空的结果。 这是我的主要方法:

    static void Main(string[] args)
    {

        // load the document
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(@"C:\Users\Hideki\ShinDeta.xml");


        Supervisor ayumi = new Supervisor();

  // this line return null 
        XmlNode ayumiNode = xmlDoc.GetElementById("1236674");

      //     ayumi.Id = (supply expression here);
     //      ayumi.Name = (supply expression here);
    //       ayumi.Contracts = (supply expression here);
   //        ayumi.Volume = (supply expression here);
  //         ayumi.Average = (supply expression here);

    }

有人能指出我实现这一目标的最短路径? 没有LINQ语法请我并不熟悉它。

Answer 1:

你可以使用Xml序列来做到这一点。 下面是一个例子

    [XmlType("supervisor")]
    public class Supervisor
    {
        [XmlAttribute("id")]
        public string Id { set; get; }

        public string Name { set; get; }

        [XmlElement("Contract")]
        public int Contracts { set; get; }

        public long Volume { set; get; }

        public int Average { set; get; }
    }

        static void Main(string[] args)
        {
            try
            {
                XmlSerializer xs = new XmlSerializer(typeof(List<Supervisor>), new XmlRootAttribute("digital-sales"));
                using (FileStream fileStream = new FileStream(@"C:\temp\ShinDeta.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var supervisors = xs.Deserialize(fileStream) as List<Supervisor>;
                    foreach (Supervisor supervisor in supervisors)
                    {
                        Debug.WriteLine($"Id: {supervisor.Id}, Name: {supervisor.Name}");
                    }
                }
            }
            catch(Exception e)
            {
                Debug.WriteLine(e.Message);
            }           
        }

这种输出:

Id: 1236674, Name: Hiroki
Id: 123459, Name: Ayumi


文章来源: How to use xml id to fill class object?
标签: c# xml object fill id