0

I am trying to serialize and deserialize responses I am getting from service. The response is xml. The problem is that response can contain namespaces.

This is a response example which contains xmlns in root element and xmlns:ns2 in child:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RootElement version="4.0" xmlns="http://www.test.com/test">
    <Verification xmlns="" xmlns:ns2="http://www.test.com/test">
    <!--some fields-->
    </Verification>
</RootElement>

This is another response which does not contain xmlns and xmlns:n2:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RootElement version="2.0">
    <Verification>
    <!--some fields-->
    </Verification>
</RootElement>

To deserialize this response and then to serialize again I am using this code:

public static object XmlDeserializeFromString(this string objectData, Type type)
{
    var serializer = new XmlSerializer(type);
    object result;
    using (TextReader textReader = new StringReader(objectData))
    {
        using (XmlTextReader xmlReader = new XmlTextReader(textReader))
        {
            // xmlReader.Namespaces = false;
            result = serializer.Deserialize(xmlReader);
        }
    }
    return result;
}
public static string XmlSerializeToString(this object objectInstance, System.Text.Encoding encoding)
{
    var serializer = new XmlSerializer(objectInstance.GetType());
    var sb = new StringBuilder();
    var settings = new XmlWriterSettings
    {
        Encoding = encoding ?? System.Text.Encoding.UTF8,
        Indent = true,
        NewLineHandling = NewLineHandling.Replace
    };
    using (var sw = new EncodedStringWriter(encoding, sb))
    {
        using (var xw = XmlWriter.Create(sw, settings))
        {
            serializer.Serialize(xw, objectInstance);
        }
    }
    return sb.ToString();
}

The class: This works for first type or responses but not for second. If I'll remove Namespace from attribute it will work for second but not for first type.

[Serializable, XmlRoot("RootElement", IsNullable = false, Namespace="http://www.test.com/test")]
public class RootElement 
{ 
    [XmlAttribute("version")] public string Version;

    [XmlElement(Namespace="http://www.test.com/test")]
    public Verification[] Verification;
}
public class Verification
{
    [XmlAttribute("vendor")] public string Vendor;
}

with xmlReader.Namespaces = false line uncommented deserialization fails for first example, with commented it fails for second example. I tried to override the NamespaceURL property from XmlTextReader to ignore namespaces like it is described here and in other questions and answers and articles, also tried to override Read() method but it does not helped. I also tried to add or remove urls from class attributes but it does not helped too. Is it possible to create a serialize and deserialize methods which can do the job for both responses? What I am doing wrong?

Gor Asatryan
  • 904
  • 7
  • 24

0 Answers0