Search code examples
c#.netxmlstringroot-node

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.


Solution

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