Using C# .Net 4 -- XML Sample (Real sample has 6 attributes)
25
I just ran a test serializing/deserializing your object and it seems to work fine
Test:
TestXML obj = new TestXML{ attr1 = "Attrib1", attr2 = "Attrib2", DateAdded = DateTime.Now, TestElement = 44};
XmlSerializer serializer = new XmlSerializer(typeof(TestXML));
using (FileStream stream = new FileStream(@"C:\StackOverflow.xml", FileMode.OpenOrCreate))
{
serializer.Serialize(stream, obj);
}
using (FileStream stream = new FileStream(@"C:\StackOverflow.xml", FileMode.Open))
{
TestXML myxml = (TestXML)serializer.Deserialize(stream);
}
all attributes deserialized ok.
Result:
Xml:
<?xml version="1.0"?>
<TestXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" attr1="Attrib1" attr2="Attrib2" DateAdded="10/01/2013 9:46:23 a.m.">
<TestElement>44</TestElement>
</TestXML>
You are defining the attributes on TestElement
while they should be on TestXML
. Example:
@"<TestXML attr1=""MyAttr"" attr2=""1"">
<TestElement>26</TestElement>
</TestXML>"
As an additional note to the accepted answer. Make sure the xml element doesn't contain a nil="true" attribute like this:
<TestXML>
<TestElement attr1="MyAttr" attr2="1" DateAdded="" xsi:nil="true">25</TestElement>
</TestXML>
From my experience the deserializer won't deserialize attributes of an element marked as null (nil).
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.