I am retrieving xml data from an http web request and deserializing the data into objects.
Here is a sample xml structure.
<users>
<user>
<name>...</name>
<orders>
<order>
<number>...</number>
</order>
...
</orders>
</user>
<user>
<name>...</name>
<orders></orders>
</user>
...
</users>
I have four classes
public class Users
{
[XmlElement("user")]
public User[] UserList { get; set; }
}
public class User
{
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("orders")]
public Orders OrderList { get; set; }
}
public class Orders
{
[XmlElement("order")]
public Order[] Order { get; set; }
}
public class Order
{
[XmlElement("number")]
public string Number { get; set; }
}
I feel like three classes should be enough - have an Order[] in User class and get rid of 'Orders' class. Is that possible? Whatever I tried did not work.
Thanks.
This should work
XmlSerializer ser = new XmlSerializer(typeof(Users));
var u = (Users)ser.Deserialize(stream);
[XmlRoot("users")]
public class Users
{
[XmlElement("user")]
public User[] UserList { get; set; }
}
public class User
{
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("orders"),XmlArrayItem("order")]
public Order[] OrderList { get; set; }
}
[XmlRoot("order")]
public class Order
{
[XmlElement("number")]
public string Number { get; set; }
}
You can use just 3 classes. All you have to do is to add Xml.Serialization.XmlType to your classes
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
[Xml.Serialization.XmlType("users", IncludeInSchema = true)]
public class Users
{
[XmlElement("user")]
public List<User> UserList {
get {
if (m_UserList == null) {
m_UserList = new List<User>();
}
return m_UserList;
}
}
private List<User> m_UserList;
}
[Xml.Serialization.XmlType("user", IncludeInSchema = true)]
public class User
{
[XmlElement("name")]
public string Name {
get { return m_Name; }
set { m_Name = value; }
}
private string m_Name;
[XmlArray("orders")]
public List<Orders> OrderList {
get {
if (m_OrderList == null) {
m_OrderList = new List<Orders>();
}
return m_OrderList;
}
}
private List<Orders> m_OrderList;
}
[Xml.Serialization.XmlType("orders", IncludeInSchema = true)]
public class Orders
{
[XmlElement("number")]
public string Number {
get { return m_Number; }
set { m_Number = value; }
}
private string m_Number;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With