I have a class defined like the following:
[XmlRoot(ElementName="state_territories")]
public class Location
{
...
}
The XML that I'm retrieving (pulled from the stream and written to the debugger using a writer) is:
<?xml version='1.0' encoding='utf-8' ?><state_territories>...</state_territories>
However, when I try to serialize my XML response such as:
var serializer = new DataContractSerializer(typeof(Location));
Locations = serializer.ReadObject(response.GetResponseStream()) as Location;
I received the following exception:
"Expecting element 'Location' from namespace 'http://schemas.datacontract.org/2004/07/App.Data.Territories'. Encountered 'Element' with name 'state_territories', namespace ''."
I'm probably missing something simple, but I had thought that if I define the XmlRoot, this would override the inferred root element Location.
Any ideas?
[XmlRoot(...)]
is only processed by XmlSerializer
:
var serializer = new XmlSerializer(typeof(Location));
Locations = (Location) serializer.Deserialize(response.GetResponseStream());
If you are processing regular xml and you need control over the names / attributes etc, then XmlSerializer
is the best choice; DataContractSerializer
offers only minimal control over the xml mapping.