Dan Hastings Dan Hastings - 1 year ago 130
JSON Question

XML String with no parent node to JSON with C#

I have an XML string that does not contain a parent node. This XML is a representation of a json request for an API. It seems pointless, but it is done this way to make it easy for non programmers to read the file. In order to convert the XML to json, pretty much everything i have seen says to convert the string to an XMLDocument and then use the following to get the json.

string jsonText = JsonConvert.SerializeXmlNode(doc);

The problem i have here is that the xml is not really valid and because of this, it cannot be converted to an xml document. What i really want is to be able to do this.

string jsonText = JsonConvert.SerializeXmlNode(doc.InnerXml);

This doesnt work since innerXML is a string and not an object. I have been able to get it to work by creating a root element and then just using a sub string to cut the resulting string, but this seems pointless. There has to be a better way to do this without having to add xml only to have to remove it from the json afterwards. Is it possible to convert a piece of xml like the xml below into json like the example below.


Converts to

"fielda": "a",
"fieldb": "b"

Answer Source

There's an overload of SerializeXmlNode that takes a boolean omitRootObject:

string jsonText = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download