[英]Deserialize xml node's attributes to class
I have two classes that look like this: 我有两个看起来像这样的类:
[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.
}
The xml I'm receiving looks like this: 我收到的xml如下所示:
<?xml version="1.0"?>
<Foo>
<BarResponse>
<Bar id="0" />
<Bar id="1" />
</BarResponse>
</Foo>
When I attempt to deseralize this, I get an instance of the "Foo" class, and bar has one element in it, with all of it's properties null or default. 当我尝试对其进行反序列化时,我得到了“ Foo”类的实例,bar中有一个元素,其所有属性均为null或default。 Where am I going wrong? 我要去哪里错了?
try this: 尝试这个:
[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.
}
You would get the same result stripping all attributes except for [XmlAttribute("id")], but I guess this is an excerpt from a context where it all is justified. 除去[XmlAttribute(“ id”)]之外的所有属性,您将得到相同的结果,但是我想这是从所有这些都合理的上下文中摘录的。
You need to add a default constructor for the Foo
class that instantiates your List<Bar>
. 您需要为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; }
}
Writes/Reads xml as: 将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.