反序列化的XML文件有多个元素的属性 - 属性不反序列化 [英] Deserializing XML File with multiple element attributes - attributes are not deserializing
本文介绍了反序列化的XML文件有多个元素的属性 - 属性不反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用C#.NET 4 - XML示例(实际样品有6个属性)
Using C# .Net 4 -- XML Sample (Real sample has 6 attributes)
<TestXML>
<TestElement attr1="MyAttr" attr2="1" DateAdded="">25</TestElement>
</TestXML>
有关我的类定义我有以下几点:
For my class definition I have the following:
public class TestXML() {
public TestXML() {}
public int TestElement {get; set;}
[XmlAttribute]
public string attr1 {get; set;}
[XmlAttribute]
public string attr2 {get; set;}
[XmlIgnore]
public DateTime DateAdded {get; set;}
[XmlAttribute("DateAdded")]
public string dateadded {
get{ return (DateAdded == null ? "" : DateAdded.ToString();}
set{ if(!value.Equals("")) DateAdded = DateTime.Parse(value);}
}
}
现在的code反序列化:
Now the code to deserialize:
string xml = "<TestXML><TestElement attr1=\"MyAttr\" attr2=\"1\" DateAdded=\"\">26</TestElement></TestXML>"
using (StringReader sr = new StringReader(xml)) {
XmlSerializer serializer = new XmlSerializer(typeof(TestXML));
TestXML myxml = (TestXML)serializer.Deserialize(sr);
}
现在我们得到的结果是(在VS观看对象):
Now the result we get is(viewing object in VS):
myxml
attr1 | null
attr2 | null
TestElement | 25
在一个完全丧失,为什么属性不会反序列化。
At a complete loss as to why the attributes will not deserialize.
推荐答案
要做到这一点,你需要两个层次:
To do that you need two levels:
[XmlRoot("TestXML")]
public class TestXml {
[XmlElement("TestElement")]
public TestElement TestElement { get; set; }
}
public class TestElement {
[XmlText]
public int Value {get;set;}
[XmlAttribute]
public string attr1 {get;set;}
[XmlAttribute]
public string attr2 {get;set;}
}
注意&GT; 26&LT;
可能会导致问题太(空白);你可能需要的是一个字符串,而不是一个int。
Note that the > 26 <
may cause problems too (whitespace); you may need that to be a string instead of an int.
这篇关于反序列化的XML文件有多个元素的属性 - 属性不反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文