c# - 如何使用 xml id 填充类对象?
问题描述
我在 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>
在 main 中,我为每个主管创建对象并通过搜索 id 填充其数据。但是我总是得到 null 结果。这是我的主要方法:
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 语法,我一点也不熟悉。
解决方案
您可以使用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
推荐阅读
- python - 应用配置中找不到指定的模块错误
- javascript - 如何使用javascript获取数组中的特定键值
- java - 编写一个添加到链表末尾的函数
- traefik - 如何配置 traefik 2.2 转发 url 和删除关键字
- validation - 在 CloudFormation 模板中输入所需的参数
- python - 从前一帧和光流创建帧
- android - Android Studio 中的 Java NullPointerException
- python - os.remove()+os.rmdir() 比 shutil.rmtree() 更好吗
- python - 如何在 Matplotlib 中禁用连接起点和终点的线?
- r - 现有条形图上的叠加线