I have some XML which I would like to serialize into a class.
<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. But I'm stumbled upon my requirement, where the XML looks like,
<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)
How do I design the classes and member variables to get the above serialized XML? (Provided, there wont be any duplicate names in the employee list)
Any help is much appreciated.
I would go with Linq2Xml in your case.
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. It shoudl be 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). 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.