1

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.

M--
  • 25,431
  • 8
  • 61
  • 93
Arnold Pistorius
  • 522
  • 4
  • 18

2 Answers2

3

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

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.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45
  • I was looking for that `defaultNamespace` attribute, but Intellisense didn't show it untill I entered a string. Thanks for the solution :) – Arnold Pistorius Nov 09 '16 at 10:33