Click here to Skip to main content
15,615,945 members
Articles / Programming Languages / XML
Technical Blog
Posted 26 Dec 2017

Tagged as



Hello XML, My Old Friend; I've Come To Encode You Again.

Rate me:
Please Sign up or sign in to vote.
4.29/5 (3 votes)
26 Dec 2017CPOL3 min read
Encoding XML again

Hello XML, My Old Friend; I've Come To Encode You Again.

Depending on how long you've been a developer, XML might be a term that sounds totally foreign. For others, it might bring back long repressed memories of some dark days.

Hello XML, My Old Friend; I've Come To Encode You Again.

In many of my encounters with developers from broad ranges of experiences, I've seen the spectrum from the die-hard JSON lovers to the folks that believe XML is the one true encoding. Either way, if you have written any web services or Web APIs over the past decade, you've likely worked with one of these before.

This post is about the middle-ground on that spectrum: converting from XML to JSON and the many potential shortcomings of going down that road.

Why Might You Ever Want To Do This?

Ever created a Word document? How about Excel? Consumed an RSS feed? Designed an SVG? Configured a .NET application? Worked with just about any of the data industry standards (e.g. HL7, etc.)

If you answer yes to any of these, then XML played a role in some way, shape, or form. It's everywhere and pretty damn good at what it does. Heck! The .NET team tried to migrate away from XML during the infancy of .NET Core and ended up crawling back and scrapping the JSON-based alternative.

Now why does that matter? Well, let's say that you are building a brand-new application using Web API. You probably are going to be going JSON all the way, which could be a problem if you need to consume some old files that are XML encoded, thankfully there's a trick for that thanks to JSON.NET, which I'll probably safely assume is in your current application:

public string ConvertXmlToJson(string xml)  
    // Load your existing XML string into an XML document
    XmlDocument document = new XmlDocument();

    // Return a JSON-encoded version of the document
    return JsonConvert.SerializeXmlNode(document);

Likewise, if you needed to convert an existing JSON string into XML, well JSON.NET has your back there once again:

public string ConvertJsonToXml(string json)  
    // Return an XML string representing the JSON data
    XNode document = JsonConvert.DeserializeXNode(json, "Root");
    return document.ToString();

That's it!

Now it's worth noting that if you are planning on returning this directly to the client to be consumed as JSON, you'll want to ensure that you have the appropriate content type set to "application/json".

Potential Bumps in The Road

As you might imagine with both these formats being so generic, there's probably a large likelihood of some crazy stuff happening during the conversion process - and you'd be right.

This Stack Overflow response from montewhizdoh does a pretty comprehensive job of explaining the major things to check for to ensure that your ride isn't too bumpy.


  • All data is stringified - All data within the XML objects will be converted to their string equivalents (e.g. "false" instead of false, "0" instead of 0, etc.) Since JavaScript treats these very differently, it's worth looking out for.
  • Children elements can become nested-object [] OR nested-array {} depending if there is only one or more than one XML child-element - A nested object and a nested array would both be consumed very differently in JavaScript, so this is something to consider. JSON.NET will recognize a json:Array='true' attribute, which can be used to work around this issue in some cases.
  • XML must be well-formed - While the XML doesn't have to perfectly conformed to standards, you must include a root element and element names cannot begin with numbers.
  • Empty elements are not converted - Any blank elements within the XML document will not be converted to JSON and are simply ignored.

JSON to XML Conversion Issues

  • A top-level element is required - Since XML expects a root element, one must be present that can be converted to the root of your XML result or the parser will fail.
  • Object names cannot begin with numbers - Your object names cannot start with a number, as they cannot be converted to elements. XML is technically more strict for this, but you can sometimes get away with breaking some of the naming rules.

I'm sure that your mileage may vary and that every scenario might require a few data massage sessions to get everything converted across as expected. Hopefully, this will give you a few things to keep on the top of your mind should you have to work with any legacy XML files in your brand new Web API application.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior)
United States United States
An experienced Software Developer and Graphic Designer with an extensive knowledge of object-oriented programming, software architecture, design methodologies and database design principles. Specializing in Microsoft Technologies and focused on leveraging a strong technical background and a creative skill-set to create meaningful and successful applications.

Well versed in all aspects of the software development life-cycle and passionate about embracing emerging development technologies and standards, building intuitive interfaces and providing clean, maintainable solutions for even the most complex of problems.

Comments and Discussions

Questionc++ Pin
dan o28-Dec-17 3:12
dan o28-Dec-17 3:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.