将嵌套的xml反序列化为C#对象

use*_*317 6 c# xml-serialization

我正在从http Web请求中检索xml数据并将数据反序列化为对象.

这是一个示例xml结构.

<users>
    <user>
        <name>...</name>
        <orders>
            <order>
                <number>...</number>
            </order>        
            ...
        </orders>
    </user>
    <user>
        <name>...</name>
        <orders></orders>
    </user>
    ...
</users>
Run Code Online (Sandbox Code Playgroud)

我有四节课

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; }
}
Run Code Online (Sandbox Code Playgroud)

我觉得三个类应该足够了 - 在User类中有一个Order []并摆脱'Orders'类.那可能吗?无论我尝试什么都行不通.

谢谢.

I4V*_*I4V 13

这应该工作

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; }
}
Run Code Online (Sandbox Code Playgroud)