How to deserialize XML when you don't know the namespace?

I am dealing with an API that changes namespaces from time to time in the XML I receive. The XML structure remains the same. I need to deserialize XML into a strongly typed model.

How do I deserialize no matter what namespace is in the XML?

I used a model like this:

[Serializable, XmlRoot(ElementName = "TestModel", Namespace = "http://schemas.datacontract.org/UnknownNamespace1")]
public class TestModel
{
    public TestModel()
    {
        TestElements = new List<TestModelChildren>();
    }

    [XmlElement("TestModelChildren")]
    public List<TestModelChildren> TestElements { get; set; }
}

      

I am trying to deserialize some XML into this model with code like this:

public TestModel DeserializeIt(XDocument xDoc)
{
    TestModel result;
    var serializer = new XmlSerializer(typeof(TestModel));

    using(var sr = new StringReader(xDoc.ToString()))
    {
        result = (TestModel)serializer.Deserialize(sr);
    }

    return result;
}

      

My problem is that every so often, the namespace in the XML I get changes. I can start getting XML like this:

<TestModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/UnknownNamespace2">
    <TestModelChildren>
        ...
    </TestModelChildren>
</TestModel>

      

I don't want to recompile my code every time this namespace change happens. How can I deal with this?

+3


source to share


1 answer


I managed to solve the problem by passing the namespace to the XmlSerializer as the default namespace. I can rip out the namespace from the XDocument to do this.

My new model will look like this without the specified namespace:

[Serializable, XmlRoot(ElementName = "TestModel")]
public class TestModel
{
    public TestModel()
    {
        TestElements = new List<TestModelChildren>();
    }

    [XmlElement("TestModelChildren")]
    public List<TestModelChildren> TestElements { get; set; }
}

      



My code for deserializing XML would look like this:

public TestModel DeserializeIt(XDocument xDoc)
{
    TestModel result;
    var serializer = new XmlSerializer(typeof(TestModel), xDoc.Root.Name.Namespace.ToString());

    using(var sr = new StringReader(xDoc.ToString()))
    {
        result = (TestModel)serializer.Deserialize(sr);
    }

    return result;
}

      

This works for me.

+3


source







All Articles