Home > OS >  Deserialize XML either with or without Namespace
Deserialize XML either with or without Namespace

Time:11-29

I have several xml files coming in. Some have namespaces, some don't. How can accurately convert these without getting an exception.

Here is my code:

SASBM XML:

<ExportData xmlns="http://www.w3.org/2001/XMLSchema-instance">
    <SASBM>...</SASBM>
</ExportData>

SASCS XML:

<ExportData>
    <SASCS>...</SASCS>
</ExportData>

My XML Deserializer:

_xmlSerializer = new XmlSerializer(typeof(ExportData));
_xmlSerializer.Deserialize(sr);

var tst = _xmlSerializer.Deserialize(sr);

And my class:

/// <remarks/>
[System.Serializable()]
[System.ComponentModel.DesignerCategory("code")]
[System.Xml.Serialization.XmlType(AnonymousType = true)]
[System.Xml.Serialization.XmlRoot(Namespace = "http://www.w3.org/2001/XMLSchema-instance", IsNullable = false)]
public partial class ExportData
{
    /// <remarks/>
    public byte PlantCode { get; set; }

    /// <remarks/>
    public byte ServerID { get; set; }

    /// <remarks/>
    public uint MessageNumber { get; set; }

    /// <remarks/>
    public ExportDataSASAH SASAH { get; set; }

    /// <remarks/>
    public ExportDataSASCS SASCS { get; set; }

    /// <remarks/>
    public ExportDataSASBM SASBM { get; set; }
}

Setting the namespace to namespace="" fixes it for one file type but then I get an exception on the second one. And I don't know of a way to add multiple namespace options.

CodePudding user response:

The solution is to override the XMLSerializer namespace function

// helper class to ignore namespaces when de-serializing
public class NamespaceIgnorantXmlTextReader : XmlTextReader
{
    public NamespaceIgnorantXmlTextReader(TextReader reader) : base(reader)
    {
    }

    public override string NamespaceURI
    {
        get { return ""; }
    }
}

Then remove the namespace attribute:

[System.Xml.Serialization.XmlRoot(Namespace = "http://www.w3.org/2001/XMLSchema-instance", IsNullable = false)]

And finally parse it as follow:

_xmlSerializer.Deserialize(new NamespaceIgnorantXmlTextReader(sr));
  • Related