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);}
}
}
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);
}
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…