Arnold Pistorius Arnold Pistorius - 4 months ago 28
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="">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:'> 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.


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


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

var serializer = new XmlSerializer(typeof(string),

And use that:

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

See this fiddle for a working demo.