我有一个带有数据的测试xml文件,并使用适当的属性设置我的对象。我没有得到任何错误,但没有任何对象在被去除后返回数据。谢谢你的帮助。
[DataContract(Name = "level1", Namespace = "")]
public class Level1
{
[DataMember(Name = "level2")]
public Level2 Level2{get;set;}
}
[DataContract(Name = "level2", Namespace = "")]
public class Level2
{
[DataMember(Name = "code")]
public string Code{get;set;}
[DataMember(Name = "global")]
public string Global{get;set;}
}
//Desrilizing Data
DataContractSerializer dcs = new DataContractSerializer(typeof(Level1));
FileStream fs = new FileStream("ExampleData/Example.xml", FileMode.OpenOrCreate);
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
Level1 p = (Level1)dcs.ReadObject(reader);//Coming back but with no values
XML
<?xml version="1.0" encoding="utf-8" ?>
<level1>
<level2 code="332443553" global="21332"/>
</level1>
答案 0 :(得分:2)
level2
的属性应该是xml元素,而不是xml属性:
<?xml version="1.0" encoding="utf-8" ?>
<level1>
<level2>
<code>332443553</code>
<global>21332</global>
</level2>
</level1>
修改强>
要使用属性进行反序列化,您必须使用XmlSerializer
而不是DataContractSerializer
,如上所述:
// Attribute on Property
[DataMember(Name = "code"), XmlAttribute]
public string Code{ get; set; }
// ...
// Deserialization
XmlSerializer serializer = new XmlSerializer(typeof(Level1));
// ...
Level1 p = (Level1)serializer.Deserialize(reader);