反序列化列表项中的列表

时间:2016-11-07 15:58:11

标签: c# xml-deserialization

我有以下示例XML。我需要反序列化它。

<?xml version="1.0" encoding="utf-16"?>
<Users filename="testfile">
    <User name="John Doe" age="51">
        <Addresses>
            <Address street="1511 Smith Pl." city="Boulder" state="CO" zip="80000" />
            <Address street="1820 Main St." city="Lafayette" state="CO" zip="80100" />
        </Addresses>
    </User>
    <User name="Jeff Jones" age="35">
        <Addresses>
            <Address street="2111 Jefferson Rd.." city="Colorado Springs" state="CO" zip="80099" />
        </Addresses>
    </User>
</Users>

我使用以下代码:

    private void button1_Click(object sender, EventArgs e)
    {
      XmlSerializer xmlIn = new XmlSerializer(typeof(UserItems));
      StreamReader srIn = new StreamReader("c:\\address.xml");
      UserItems uiItems;

      uiItems = (UserItems)xmlIn.Deserialize(srIn);

      srIn.Close();
    }
  }

  [XmlRoot("Users")]
  public class UserItems
  {
    private List<UserItem> p_liUserItems;

    [XmlAttribute("filename")] public string FileName { get; set; }

    [XmlElement("User")]
    public List<UserItem> Users
    {
      get
      {
        return p_liUserItems;
      }
      set
      {
        p_liUserItems = value;
      }
    }
  }

  [Serializable]
  public class UserItem
  {
    private List<AddressItem> p_liAddressItems = new List<AddressItem>();

    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlAttribute("age")]
    public string Age { get; set; }

    [XmlElement("Address")]
    public List<AddressItem> Addresses
    {
      get
      {
        return p_liAddressItems;
      }
      set
      {
        p_liAddressItems = value;
      }
    }
  }

  [Serializable]
  public class AddressItem
  {
    [XmlAttribute("street")]
    public string Street { get; set; }
    [XmlAttribute("city")]
    public string City { get; set; }
    [XmlAttribute("state")]
    public string State { get; set; }
    [XmlAttribute("zip")]
    public string ZipCode { get; set; }
  }

这可以很好地反序列化。我得到每个用户的信息,但我没有得到每个用户的任何地址。每个用户都有一个空白地址列表如何对集合项中的集合进行反序列化?

1 个答案:

答案 0 :(得分:1)

您的AddressesXmlElement,但是包裹数组的XmlArray。您可以使用XmlArrayItemAddresses(de)对其进行序列化,以防止必须为[XmlArray("Addresses")] [XmlArrayItem("Address")] public List<AddressItem> Addresses { get { return p_liAddressItems; } set { p_liAddressItems = value; } } 创建和修饰包装类:

[Serializable]
public class UserItem
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlAttribute("age")]
    public string Age { get; set; }

    [XmlElement("Addresses")]
    public AddressWrapper Addresses { get; set; }
}

[Serializable]
public class AddressWrapper
{
    [XmlElement("Address")]
    public List<AddressItem> Addresses { get; set; }
}

或者,如果你想要包装类:

getCallingPackage

另见Wrapping Serialized Array Elements with the Name of the Array