我如何在c#中反序列化数组数组?

时间:2012-10-03 19:52:09

标签: c# xml xml-serialization

我正在尝试对信用卡分档的对象进行反序列化,以便在表单上进行品牌验证,但无法正确完成。内部对象不反序列化,或者主要品牌列表为空。任何人都可以给我一两手牌吗?

我的XML是这样的:

<?xml version="1.0" encoding="utf-8"?>
<Brands>
  <Brand type="visa">
    <Bins>
      <Bin enabled="true" value="123" />
      <Bin enabled="true" value="456" />
      <Bin enabled="true" value="789" />
    </Bins>
  </Brand>
  <Brand type="master">
    <Bins>
      <Bin enabled="true" value="987" />
      <Bin enabled="true" value="654" />
      <Bin enabled="true" value="321" />
    </Bins>
  </Brand>
</Brands>

我的最新代码(带来brandsCollection null )是:

[XmlRoot("Brands")]
public class CreditCardBrand
{
    [XmlArray("Brands"), XmlArrayItem("Brand")]
    public CreditCardBrandCollection[] brandsCollection { get; set; }
}

public class CreditCardBrandCollection
{
    [XmlElement("Bins")]
    public CreditCardBrandBins[] binsCollection { get; set; }

    [XmlAttribute("type")]
    public CreditCardBrands brand { get; set; }
}

public class CreditCardBrandBins
{
    [XmlAttribute("value")]
    public string bin { get; set; }

    [XmlAttribute("enabled")]
    public bool enabled { get; set; }
}

我想将这个xml反序列化为一个Brands数组,每个品牌都有一个属性名称(类型)和一个与它们相关联的bin(只有已启用的)数组,所以我可以把它放在我系统的内存中启动。

2 个答案:

答案 0 :(得分:2)

实际上很容易。您只是混淆 - 或者,更好地说,重复 - 根元素声明和brandsCollection数组的归属方式。您必须按如下方式更改声明:

[XmlRoot("Brands")]
public class CreditCardBrand
{
    [XmlElement("Brand")]
    public CreditCardBrandCollection[] brandsCollection { get; set; }
}

此处[XmlElement]导致数组的每个元素由单个<Brand>标记表示。在原始代码中,您描述了一个XML,它必须如下所示:

<Brands>
    <Brands> <!-- duplicate Brands element here -->
        <Brand type="…">…</Brand>
        <Brand type="…">…</Brand>
        <Brand type="…">…</Brand>
        …
    </Brands>
</Brands>

答案 1 :(得分:2)

如果您想使用Linq2Xml

XDocument xDoc = XDocument.Parse(xml); //or XDocument.Load(filename)
List<CreditCardBrand> brands =
            xDoc.Descendants("Brand")
            .Select(br => new CreditCardBrand()
            {
                Type = br.Attribute("type").Value,
                Bins = br.Descendants("Bin")
                            .Select(b => new CreditCardBin(){
                                Enabled = (bool)b.Attribute("enabled"),
                                Value = b.Attribute("value").Value,
                            }).Where(b => b.Enabled == true)
                            .ToList()

            })
            .ToList();

-

public class CreditCardBrand
{
    public string Type { get; set; }
    public List<CreditCardBin> Bins { get; set; }
}

public class CreditCardBin
{
    public string Value { get; set; }
    public bool Enabled { get; set; }
}