Arnold Pistorius Arnold Pistorius - 26 days ago 11
C# Question

How to Deserialize a XML response when the root node is a string in C#

The Microsoft Cognitive Text Translator API gives a response in the following format:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">nl</string>


I was trying to deserialize it with the following code:

var serializer = new XmlSerializer(typeof(string));
var stringReader = new StringReader(xmlResult); // xmlResult is the xml string above
var textReader = new XmlTextReader(stringReader);
var result = serializer.Deserialize(textReader) as string;


But this will result in an exception:


System.InvalidOperationException: There is an error in XML document (1, 23). ---> System.InvalidOperationException: http://schemas.microsoft.com/2003/10/Serialization/'> was not expected.


I was thinking of wrapping the api response xml in another root node, so I could parse it to an object. But there must be a better way to solve this.

I appreciate your help to solve my issue.

Answer

The issue you have is the namespace. If you serialised a value using that serialiser, you'd get:

<string>nl</string>

So set the default namespace to the one in your XML:

var serializer = new XmlSerializer(typeof(string),
     "http://schemas.microsoft.com/2003/10/Serialization/");

And use that:

using (var reader = new StringReader(xmlResult))
{
    var result = (string)serializer.Deserialize(reader);
}

See this fiddle for a working demo.

Comments