[英]how to get XML attribute using XmlSerializer in c#
我有我用来获取值的此类和xml文件。
<Task>
<Employee Id="123">
<string>/Name</string>
<string>/Company</string>
</Employee>
<Manager Id="456">
<string>/Name</string>
<string>/Company</string>
</Manager>
</Task>
public class Task
{
public List<string> Employee;
public List<string> Manager;
}
var taks = (Task)new XmlSerializer(typeof(Task)).Deserialize(streamReader);
因此,在任务中,我正在正确获取名称和公司名称为Employee的列表。 我想获取每个元素的ID。 我怎么得到它?
/名称和/公司可以是任何东西。 我可以在其中放置任何值,而无需为它创建属性就可以在员工中获取它。 Manager也是如此,我可以拥有/ Email,/ Website,/ LastLogin等,并且即使没有为其创建属性,也可以在Manager对象中获得它。
感谢您的时间和帮助。
如下定义您的Task
类:
public class Task
{
public Employee Employee;
public Manager Manager;
}
Employee
在哪里:
public class Employee
{
[XmlAttribute]
public string Id {get;set;}
public string Name{get;set;}
public string Company{get;set;}
}
Manager
是:
public class Manager
{
[XmlAttribute]
public string Id {get;set;}
public string Name{get;set;}
public string Company{get;set;}
}
如果您对Employee
和/或Manager
的通用属性列表感兴趣,请考虑使用另一个名为Property
类,如下所示:
public class Property
{
[XmlAttribute]
public string Value{get;set;}
}
然后,将您的Manager
和Employee
更改为以下内容:
public class Employee
{
[XmlAttribute]
public string Id {get;set;}
public List<Property> Properties {get;set;}
}
public class Manager
{
[XmlAttribute]
public string Id {get;set;}
public List<Property> Properties {get;set;}
}
最后,将您的XML更改为以下内容:
<Task>
<Employee Id="123">
<Properties>
<Property Value="/Name" />
<Property Value="/Company"/>
</Properties>
</Employee>
<Manager Id="456">
<Properties>
<Property Value="/Name" />
<Property Value="/Company"/>
</Properties>
</Manager>
</Task>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.