How can I deserialize an object from an XML string?
I'm trying to deserialize an object back from it's XML string using xmlSerializer.Deserialize() but the returned object is always blank开发者_Go百科 (not null, but all the properties are null or 0). I can't work out what I'm doing wrong and yet I get no errors or exceptions.
string xml = "***my xml is here***";
XmlSerializer ser = new XmlSerializer(typeof(Order));
StringReader stringReader = new StringReader(xml);
XmlTextReader xmlReader = new XmlTextReader(stringReader);
Order order = (Order)ser.Deserialize(xmlReader);
xmlReader.Close();
stringReader.Close();
The source of Order.cs was generated from the XSD using the the xsd.exe tool.
Source of order.cs: http://www.nickgilbert.com/etc/1/Order.txt
Sample order XML: http://www.nickgilbert.com/etc/1/example-order.xml
Your sample XML file (example-order.xml) uses the namespace http://tempuri.org/OrderSchema.xsd
but the code generated by XSD (order.cs) defines all of the elements in the namespace http://x-rm.com/wrightcottrell/cataloguecd/
.
You'll need these namespaces to match up in order for serialization to work properly.
The fact that you get an object back at all tells me that the object is public and has a public parameterless constructor (otherwise an exception would have been thrown). So, it is most-likely failing one of:
- deserialization members must be either public properties with public
get
and publicset
, or public (non-readonly) fields - by default the member-names must be an exact match for xml element names, in the same xml-namespace as the parent element; finer control can be obtained via attributes (changing the name, using attributes, namespaces, etc)
精彩评论