3

フォームでブランドを検証するためにクレジット カード ビンのオブジェクトをデシリアライズしようとしていますが、正しく実行できません。内部オブジェクトが逆シリアル化されないか、ブランドのメイン リストが null になります。誰か手を貸してくれませんか?

私の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 をブランドの配列にデシリアライズし、各ブランドにプロパティ名 (タイプ) とビン (有効なもののみ) の配列を関連付けて、起動時にシステムのメモリに配置できるようにします。

4

2 に答える 2

2

実際には非常に簡単です。brandsCollectionルート要素の宣言と配列に属性を付ける方法を混乱させているだけです。次のように宣言を変更する必要があります。

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

ここでは、配列の各要素が 1 つのタグ[XmlElement]で表されます。<Brand>元のコードでは、次のような XML を記述しました。

<Brands>
    <Brands> <!-- duplicate Brands element here -->
        <Brand type="…">…&lt;/Brand>
        <Brand type="…">…&lt;/Brand>
        <Brand type="…">…&lt;/Brand>
        …
    </Brands>
</Brands>
于 2012-10-03T20:19:57.380 に答える
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; }
}
于 2012-10-03T20:20:34.610 に答える