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

本文关键字:xml 对象 反序列化 嵌套 序列化 | 更新日期: 2023-09-27 17:58:38

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

下面是一个示例xml结构。

<users>
    <user>
        <name>...</name>
        <orders>
            <order>
                <number>...</number>
            </order>        
            ...
        </orders>
    </user>
    <user>
        <name>...</name>
        <orders></orders>
    </user>
    ...
</users>

我有四个班

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; }
}

我觉得三个类就足够了——在User类中有一个Order[],去掉"Orders"类。这可能吗?无论我试了什么都没用。

谢谢。

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

这应该能在中工作

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; }
}

您只能使用3个类。您所要做的就是将Xml.Serialization.XmlType添加到类中

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;
}