ArgusMagnus
ArgusMagnus

Reputation: 669

Json XmlDictionaryReader unable to read values which include white spaces

Im trying to read a json file with a XmlDictionaryReader created with JsonReaderWriterFactory.CreateJsonReader. It works well, as long as the values (strings) do not contain white spaces. Otherwise however, I get a weird XmlException telling me that names must not contain white spaces.

The exception is thrown when accessing the XElement.Value property, what is really weird though is that the property value is accessible and shows the correct value in the debugger.

What is going on here, is this a bug in the JSON XmlDictionaryReader?

JSON:

{
    "Names": {
        "Test": { "de": "Hallo space" }
    }
}

C#:

// using System;
// using System.Collections.Generic;
// using System.IO;
// using System.Runtime.Serialization;
// using System.Runtime.Serialization.Json;
// using System.Xml;
// using System.Xml.Linq;
// using System.Linq;

using (var inputStream = File.Open(jsonFile, FileMode.Open))
{
    var doc = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(inputStream, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null));
    foreach (var classNode in doc.Root.Elements())
    {
        foreach (var element in classNode.Elements())
        {
            var defaultValue = element.Name;
            foreach (var desc in element.Descendants())
            {
                if (!desc.HasElements)
                {
                    defaultValue = desc.Value; // throws exception
                    break;
                }
            }
            //var defaultValue = element.Descendants().FirstOrDefault(x => !x.HasElements)?.Value ?? element.Name;
        }
    }
}

Upvotes: 1

Views: 496

Answers (1)

Tewr
Tewr

Reputation: 3853

Your error is not in the reader, but how you store the values. This:

    var defaultValue = element.Name;

Can be rewritten as

    XName defaultValue = element.Name;

Later on you are thus trying to an implicit cast. The explicit cast is:

defaultValue = (XName)"Hallo space"; 

..which yields the exception. So the solution is simply...

    var defaultValue = element.Name.ToString();

Upvotes: 3

Related Questions