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.
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;} }
Note that the > 26 <
may cause problems too (whitespace); you may need that to be a string instead of an int.
You are defining the attributes on TestElement
while they should be on TestXML
. Example:
@"<TestXML attr1=""MyAttr"" attr2=""1""> <TestElement>26</TestElement> </TestXML>"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With