1

我有两个看起来像这样的类:

[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 或默认值。我哪里错了?

4

2 回答 2

1

试试这个:

[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")] 之外,您会得到相同的结果,除掉 [XmlAttribute("id")] 之外的所有属性,但我想这是从上下文中摘录的,这一切都是合理的。

于 2012-10-29T12:50:24.063 回答
0

您需要为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>
于 2012-10-29T13:17:02.633 回答