将xml节点的属性反序列化为类

时间:2012-10-29 12:34:18

标签: c# .net xml xml-deserialization

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

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

2 个答案:

答案 0 :(得分: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.
}
  • 您可以找到有关使用XmlRoot here
  • 的信息 如果您希望数组包含不同类型,则使用
  • ArrayItemAttribute

除了[XmlAttribute(“id”)]之外,您将获得剥离所有属性的相同结果,但我想这是一个完全符合上下文的上下文的摘录。

答案 1 :(得分:0)

您需要为实例化Foo的{​​{1}}类添加默认构造函数。

List<Bar>

将xml写入/读取为:

[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; }
}