Arnold Pistorius
Arnold Pistorius

Reputation: 532

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: 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.

Upvotes: 1

Views: 2133

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

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

Considering it is always valid XML fragment having a single string node, you may safely use

var result = XElement.Parse(xmlResult).Value;

When parsing the XML string with XElement.Parse, you do not have to care about the namespace.

Upvotes: 3

Charles Mager
Charles Mager

Reputation: 26223

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.

Upvotes: 1

Related Questions