繁体   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