简体   繁体   English

XML将成员变量序列化为xmlnode

[英]XML Serialization of member variable as xmlnode

I have some XML which I would like to serialize into a class. 我有一些XML,我想序列化到一个类。

<Group>
 <Employees>
     <Employee>
         <Name>Hari</Name>
         <Age>30</Age>
     </Employee>
     <Employee>
         <Name>Yougov</Name>
         <Age>31</Age>
     </Employee>
     <Employee>
         <Name>Adrian</Name>
         <Age>28</Age>
     </Employee>
</Employees >

The above XML can be realized in C# pretty much easily. 上面的XML可以很容易地在C#中实现。 But I'm stumbled upon my requirement, where the XML looks like, 但我偶然发现了我的要求,XML的样子,

<Group>
 <Employees>
    <Hari Age=30 />
    <Yougov Age=31 />
    <Adrian Age=28 />
 </Employees >
</Group>

Where Employees is a List<Employee> with KeyValuePair<string, int>("Hari", 30) Employees是List<Employee>KeyValuePair<string, int>("Hari", 30)

How do I design the classes and member variables to get the above serialized XML? 如何设计类和成员变量以获取上面的序列化XML? (Provided, there wont be any duplicate names in the employee list) (前提是,员工名单中不会有任何重复的名称)

Any help is much appreciated. 任何帮助深表感谢。

* Serializing KeyValuePair * 序列化KeyValuePair

I would go with Linq2Xml in your case. 在你的情况下,我会选择Linq2Xml。

XDocument xDoc = XDocument.Load(......);
var emps = xDoc.Descendants("Employees").Elements()
    .Select(x => new Employee() { 
                        Name = x.Name.ToString(), 
                        Age = int.Parse(x.Attribute("Age").Value) 
                    })
    .ToList();

PS: Age=30 is not valid. PS: Age=30无效。 It shoudl be Age="30" 它应该是Age="30"

It is not a good idea to use the data as the schema; 将数据用作模式不是一个好主意; in particular, an awful lot of names are not valid as xml element names, but also: it just isn't good practice (for example, it makes it virtually useless in terms of schema validation). 特别是,许多名称作为xml元素名称无效 ,但也是:它只是不好的做法(例如,它使它在模式验证方面几乎无用)。 If you want to be terse, maybe something like: 如果你想要简洁,可能是这样的:

<Employees>
    <Add Name="Hari" Age="30" />
</Employees>

or 要么

<Employees>
    <Employee Name="Hari" Age="30" />
</Employees>

which can be done simply with: 这可以简单地用:

[XmlArray("Employees"), XmlArrayItem("Employee")]
public List<Employee> Employees {get;set;}

and: 和:

public class Employee {
    [XmlAttribute]
    public string Name {get;set;}
    [XmlAttribute]
    public int Age {get;set;}
}

XmlSerializer does not support the "content as an element name" serializer, unless you do everything yourself with IXmlSerializable from the parent element (it would have to be from the parent, as XmlSerializer would have no way of identifying the child to handle there). XmlSerializer不支持“内容作为元素名称”序列化程序,除非您使用来自父元素的 IXmlSerializable自己完成所有操作(它必须来自父元素 ,因为XmlSerializer无法识别要处理的子元素 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM