1

我有一个包含数据的测试 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>
4

1 回答 1

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);
于 2013-09-22T18:54:35.693 回答