使用 C# .Net 4 -- XML 示例(真实示例有 6 个属性)
<TestXML>
<TestElement attr1="MyAttr" attr2="1" DateAdded="">25</TestElement>
</TestXML>
对于我的类定义,我有以下内容:
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);}
}
}
现在反序列化的代码:
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 中查看对象):
myxml
attr1 | null
attr2 | null
TestElement | 25
完全不知道为什么属性不会反序列化。