Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing XML File with multiple element attributes - attributes are not deserializing

Tags:

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.

like image 452
Richard Wheeler Avatar asked Jan 09 '13 20:01

Richard Wheeler


2 Answers

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.

like image 96
Marc Gravell Avatar answered Sep 17 '22 12:09

Marc Gravell


You are defining the attributes on TestElement while they should be on TestXML. Example:

@"<TestXML attr1=""MyAttr"" attr2=""1"">       <TestElement>26</TestElement>   </TestXML>" 
like image 40
Mir Avatar answered Sep 17 '22 12:09

Mir