Kokirala Sudheer
Kokirala Sudheer

Reputation: 439

Json Attributes are generating as Nodes

I need to convert a incoming json file to XML.

I am using the following code to achieve the requirement. I am using Newtonsoft Json Converter

 XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);

And the input file is

{"menu": {   "id": "file",   "value": "File",   "popup": {     "menuitem": [       {"value": "New", "onclick": "CreateNewDoc()"},       {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}  ]  }}}

And the output I am getting is

<menu><id>file</id><value>File</value><popup><menuitem><value>New</value><onclick>CreateNewDoc()</onclick></menuitem><menuitem><value>Open</value><onclick>OpenDoc()</onclick></menuitem><menuitem><value>Close</value><onclick>CloseDoc()</onclick></menuitem></popup></menu>

So here the attributes are generating as Nodes.

Thanks in Advance

Upvotes: 3

Views: 541

Answers (2)

dbc
dbc

Reputation: 116990

From Converting between JSON and XML:

Conversion Rules

  • Attributes are prefixed with an @ and should be at the start of the object.

Thus you could use Linq to JSON to modify all JSON properties with primitive values and prepend an @ character to their names. Note that, since your file will be "in MB's", you should avoid loading to a temporary string and instead stream the file contents in directly:

        // Load the JObject directly from a file
        using (var streamReader = File.OpenText(fileName))
        using (var jsonReader = new JsonTextReader(streamReader))
        {
            obj = JObject.Load(jsonReader);
        }

        // Rename all properties with primitive values (string, number, boolean, null) to begin with "@"
        foreach (var o in obj.Descendants().OfType<JObject>())
        {
            // Attributes must appear first in the JObject's property list.
            int insertIndex = 0;
            foreach (var property in o.Properties().Where((p => p.Value is JValue && !p.Name.StartsWith("@"))).ToList())
            {
                property.Remove();
                ((IList<JToken>)o).Insert(insertIndex++, new JProperty("@" + property.Name, property.Value));
            }
        }

        // Convert to XmlDocument
        XmlDocument doc;
        using (var reader = obj.CreateReader())
        {
            doc = (XmlDocument)JsonExtensions.DeserializeXmlNode(reader);
        }

Using the helper methods:

public static class JsonExtensions
{
    public static XmlDocument DeserializeXmlNode(JsonReader reader)
    {
        return DeserializeXmlNode(reader, null, false);
    }

    public static XmlDocument DeserializeXmlNode(JsonReader reader, string deserializeRootElementName, bool writeArrayAttribute)
    {
        var converter = new Newtonsoft.Json.Converters.XmlNodeConverter() { DeserializeRootElementName = deserializeRootElementName, WriteArrayAttribute = writeArrayAttribute };
        var jsonSerializer = JsonSerializer.CreateDefault(new JsonSerializerSettings { Converters = new JsonConverter[] { converter } });
        return (XmlDocument)jsonSerializer.Deserialize(reader, typeof(XmlDocument));
    }
}

This produces the output:

<menu id="file" value="File">
  <popup>
    <menuitem value="New" onclick="CreateNewDoc()" />
    <menuitem value="Open" onclick="OpenDoc()" />
    <menuitem value="Close" onclick="CloseDoc()" />
  </popup>
</menu>

Upvotes: 2

Vova
Vova

Reputation: 1416

You should append @ before attribute names.

Like this:

{"menu": { "@id": "file", "@value": "File", "popup": { "menuitem": [ {"@value": "New", "@onclick": "CreateNewDoc()"}, {"@value": "Open", "@onclick": "OpenDoc()"}, {"@value": "Close", "@onclick": "CloseDoc()"} ] }}}

This will create the following XML:

<menu id="file" value="File">
    <popup>
        <menuitem value="New" onclick="CreateNewDoc()" />
        <menuitem value="Open" onclick="OpenDoc()" />
        <menuitem value="Close" onclick="CloseDoc()" />
    </popup>
</menu>

If you do not have control over JSON then you can modify it programmatic before converting into XML like this:

json = json.Replace("id", "@id").Replace("value", "@value").Replace("onclick", "@onclick");

Or you can transform XML after conversion using XSLT.

Upvotes: 2

Related Questions