I've got a Stream containing xml in the following format that I want to deserialize into C# objects
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<OrganisationMetaData xmlns="urn:organisationMetaDataSchema">
<Organisations>
<Organisation>
<Code>XXX</Code>
<Name>Yyyyyy</Name>...
I've done this loads of times with strings, but with the stream it is kindly appending the namespace attribute to all the complex elements. If I just remove the xmlns attribute, and forget about validating it against a schema, it just appends an empty xmlns attribute. The problem I have is that the Deserialize method in XmlSerializer (?), throws an error saying it doesn't expect the attribute. I have tried decorating the class with the XmlRoot and XmlType attributes but this didn't change anything.
Here's the class I want to deserialize into
[XmlRoot(
ElementName = "OrganisationMetaData",
Namespace = "urn:organisationMetaDataSchema")]
public class OrganisationMetaData
{
public List<Organisation> Organisations { get; set; }
}
[XmlType(
TypeName = "Organisation",
Namespace = "urn:organisationMetaDataSchema")]
public class Organisation
{
public string Code {get; set;}
public string Name {get; set;}
}
Here's the method that is being used to do the work
public IList<Organisation> DeserializeOrganisations(Stream stream)
{
var serializer = new XmlSerializer(typeof(OrganisationMetaData));
var mappingAssembly = //Resource in another assembly
var schemas = new XmlSchemaSet();
schemas.Add(
"urn:organisationMetaDataSchema",
XmlReader.Create(
mappingAssembly.GetManifestResourceStream(
// An xml schema
)
)
);
var settings = new XmlReaderSettings()
{
ValidationType = ValidationType.Schema,
Schemas = schemas,
ValidationFlags =
XmlSchemaValidationFlags.ReportValidationWarnings
};
settings.ValidationEventHandler += settings_ValidationEventHandler;
var reader = XmlReader.Create(stream, settings);
var metaData= (OrganisationMetaData)serializer.Deserialize(reader);
return metaData.Organisations.ToList();
}
I've tried this using DataContractSerializer but that brings it's own oppotunities to learn, so if anyone could help with what I ought to be putting in the attributes to get XmlSerializer to work, it would be great.
Any help would be appreciated, thanks.