簡體   English   中英

將xml節點的屬性反序列化為class

[英]Deserialize xml node's attributes to class

我有兩個看起來像這樣的類:

[XmlRoot("Foo")]
public class Foo
{
    [XmlArray("BarResponse")]
    [XmlArrayItem("Bar")]
    public List<Bar> bar {get; set;}
    //some other elements go here.
}

[XmlRoot("Bar")]
public class Bar
{
    [XmlAttribute("id")]
    public Int32 Id {get; set;}
    //some other elements go here.
}

我收到的xml如下所示:

<?xml version="1.0"?>
<Foo>
    <BarResponse>
        <Bar id="0" />
        <Bar id="1" />
    </BarResponse>
</Foo>

當我嘗試對其進行反序列化時,我得到了“ Foo”類的實例,bar中有一個元素,其所有屬性均為null或default。 我要去哪里錯了?

嘗試這個:

[TestFixture]
public class BilldrTest
{
    [Test]
    public void SerializeDeserializeTest()
    {
        var foo = new Foo();
        foo.Bars.Add(new Bar { Id = 1 });
        foo.Bars.Add(new Bar { Id = 2 });
        var xmlSerializer = new XmlSerializer(typeof (Foo));
        var stringBuilder = new StringBuilder();
        using (var stringWriter = new StringWriter(stringBuilder))
        {
            xmlSerializer.Serialize(stringWriter, foo);
        }
        string s = stringBuilder.ToString();
        Foo deserialized;
        using (var stringReader = new StringReader(s))
        {
            deserialized = (Foo) xmlSerializer.Deserialize(stringReader);
        }
        Assert.AreEqual(2,deserialized.Bars.Count);
    }
}

[XmlRoot("Foo")]
public class Foo
{
    public Foo()
    {
        Bars= new List<Bar>();
    }
    [XmlArray("BarResponses")]
    [XmlArrayItem(typeof(Bar))]
    public List<Bar> Bars { get; set; }
    //some other elements go here.
}

[XmlRoot("Bar")]
public class Bar
{
    [XmlAttribute("id")]
    public Int32 Id { get; set; }
    //some other elements go here.
}

除去[XmlAttribute(“ id”)]之外的所有屬性,您將得到相同的結果,但是我想這是從所有這些都合理的上下文中摘錄的。

您需要為Foo類添加一個默認的構造函數,以實例化List<Bar>

[Serializable]
public class Foo
{
    public Foo()
    {
        Bar = new List<Bar>();
    }

    [XmlArray("BarResponse")]
    [XmlArrayItem("Bar")]
    public List<Bar> Bar { get; set; }
}

[Serializable]
public class Bar
{
    [XmlAttribute("id")]
    public Int32 Id { get; set; }
}

將xml寫入/讀取為:

<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <BarResponse>
    <Bar id="0" />
    <Bar id="1" />
  </BarResponse>
</Foo>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM