328

I started to use Json.NET to convert a string in JSON format to object or viceversa. I am not sure in the Json.NET framework, is it possible to convert a string in JSON to XML format and viceversa?

Termininja
  • 6,620
  • 12
  • 48
  • 49
David.Chu.ca
  • 37,408
  • 63
  • 148
  • 190
  • Note as StaxMan said, if there's ex. space in the element node, it will be ignored by xml. For ex. "Student Id": 11000 won't be in xml result bcuz of space in property name. xml doesn't accept having space within Element Node. – Daniel B Aug 20 '18 at 19:12
  • QuickAnswer: If you look and the documentation you can convert `JSON to Xml` as https://www.newtonsoft.com/json/help/html/ConvertJsonToXml.htm and `Xml to JSON` as https://www.newtonsoft.com/json/help/html/ConvertXmlToJson.htm – Vinod Srivastav Apr 03 '23 at 12:01

12 Answers12

479

Yes. Using the JsonConvert class which contains helper methods for this precise purpose:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

Documentation here: Converting between JSON and XML with Json.NET

weston
  • 54,145
  • 21
  • 145
  • 203
David Brown
  • 35,411
  • 11
  • 83
  • 132
  • 3
    I could not find this class. I use NewtonSoft Json.net 3.5. – David.Chu.ca May 02 '09 at 18:51
  • 3
    It appears this functionality has been moved to the Newtonsoft.Json.Converters.XmlNodeConverter class in JSON.NET 3.5: http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_Converters_XmlNodeConverter.htm – David Brown May 02 '09 at 20:01
  • I looked at there but your examples codes are not there. Any example codes to use the new libraries to do the conversions? – David.Chu.ca May 03 '09 at 00:07
  • The link I posted in my previous comment has all of the information you need. But I'll edit my answer anyway... – David Brown May 03 '09 at 01:09
  • 4
    Just FYI, there's a potential issue here. When I was turning an array of xml nodes to json it was making an array in json. But, when I run through an array of xml nodes that have a count of 1, then the json conversion doesn't format an array anymore. An xml array with a single element gets lost in translation here. – Levitikon Mar 22 '12 at 21:11
  • 3
    Surprise surprise -- this is the impedance between XML and JSON, and the reason why it is (IMO) not a good idea to _directly_ convert between the two. But, hey, there are lots of devs who strongly disagree here (as per downvotes on my answer) and don't mind these accidental data conversions or potential data loss... – StaxMan Aug 01 '12 at 01:41
  • 7
    @StaxMan: I think everyone can agree that there's no standardized way to represent an XML document in JSON format. Your answer was probably downvoted because it didn't actually answer the question. The OP wasn't asking if he *should* do the conversion, but rather if he *could* do it using tools already at his disposal. – David Brown Aug 01 '12 at 03:08
  • Fair enough. Although I did edit it to mention that IMO one should go via Object (or, something else to obtain more metadata). In many cases one does not have convert directly between the two, but rather produce either or... but there are then legacy cases where conversion is necessary. – StaxMan Aug 01 '12 at 18:23
  • Just realized that I also should have addressed "didn't ask if X good, but how to X" -- actually, I think it is important to address that also, for cases where one feels doing X is an anti-pattern. And I strongly feel this is the case here (having done tons of XML and JSON processing, written tools etc). FWIW. – StaxMan Aug 13 '13 at 22:55
  • can this be done using an xml string? i need to convert xml to json, but the xml is not valid (no root node). This means i cannot convert the xml to an object before sending it to be parsed to json – Dan Hastings Jun 30 '15 at 08:50
  • Hello Friends, here convert is successfully JSON to XML. And Now its store in one text file extension with .xml it is possible. – Nikunj Chaklasiya Jun 24 '19 at 09:52
  • Created online tools to convert XML to JSON with the help of above code, if anyone wants to test and check output, here is the link https://www.minify-beautify.com/convert-xml-to-json-online – Vikas Lalwani Jan 31 '21 at 15:23
60

Yes, you can do it (I do) but Be aware of some paradoxes when converting, and handle appropriately. You cannot automatically conform to all interface possibilities, and there is limited built-in support in controlling the conversion- many JSON structures and values cannot automatically be converted both ways. Keep in mind I am using the default settings with Newtonsoft JSON library and MS XML library, so your mileage may vary:

XML -> JSON

  1. All data becomes string data (for example you will always get "false" not false or "0" not 0) Obviously JavaScript treats these differently in certain cases.
  2. Children elements can become nested-object {} OR nested-array [ {} {} ...] depending if there is only one or more than one XML child-element. You would consume these two differently in JavaScript, etc. Different examples of XML conforming to the same schema can produce actually different JSON structures this way. You can add the attribute json:Array='true' to your element to workaround this in some (but not necessarily all) cases.
  3. Your XML must be fairly well-formed, I have noticed it doesn't need to perfectly conform to W3C standard, but 1. you must have a root element and 2. you cannot start element names with numbers are two of the enforced XML standards I have found when using Newtonsoft and MS libraries.
  4. In older versions, Blank elements do not convert to JSON. They are ignored. A blank element does not become "element":null

A new update changes how null can be handled (Thanks to Jon Story for pointing it out): https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm

JSON -> XML

  1. You need a top level object that will convert to a root XML element or the parser will fail.
  2. Your object names cannot start with a number, as they cannot be converted to elements (XML is technically even more strict than this) but I can 'get away' with breaking some of the other element naming rules.

Please feel free to mention any other issues you have noticed, I have developed my own custom routines for preparing and cleaning the strings as I convert back and forth. Your situation may or may not call for prep/cleanup. As StaxMan mentions, your situation may actually require that you convert between objects...this could entail appropriate interfaces and a bunch of case statements/etc to handle the caveats I mention above.

DaFi4
  • 1,364
  • 9
  • 21
  • 2
    This! Nice elaboration of what my short (and heavily downvoted at some point) answer was based on -- there are many, many pitfalls if you do blind direct conversion. They may not be blocking issues for specific usage, but can also be very nasty for others. – StaxMan Jan 12 '16 at 21:46
  • 2
    Regarding #4 on XML -> JSON: you can use the NullValueHandling property to specify that null values should be included explicitly - https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm – Jon Story Jan 10 '19 at 14:40
  • The description of the problem in this commentary applies well to ALL implementations of algorithms which convert JSON to XML or the reverse. Once one accepts that it is not *possible* simultaneously achieve perfect bi-directional fidelity, and at the same time ether "party" or "constrained" (pre-dictated schema/format) input and output. -- in the general case. – DALDEI Apr 27 '19 at 04:35
43

You can do these conversions also with the .NET Framework:

JSON to XML: by using System.Runtime.Serialization.Json

var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
    Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));

XML to JSON: by using System.Web.Script.Serialization

var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));

private static Dictionary<string, object> GetXmlData(XElement xml)
{
    var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
    if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
    else if (!xml.IsEmpty) attr.Add("_value", xml.Value);

    return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}
Termininja
  • 6,620
  • 12
  • 48
  • 49
  • I get an error on GetXmlData "The name 'GetXmlData' does not exist in the current context" Is there a using directive that I'm missing? – TimSmith-Aardwolf Jul 21 '16 at 14:09
  • 6
    @TimSmith-Aardwolf, [Here](http://pastebin.com/yRpC5Rde) is all code you need. For **using System.Web.Script.Serialization** need to add **System.Web.Extensions** assembly in References. – Termininja Jul 21 '16 at 15:12
  • @Termininja, Perfect, Thanks. – cracker Aug 30 '16 at 04:34
  • `.NET Framework` is not `Json.NET` you are not attempting to answer the original question as to how to do it with `Json.NET` rather suggesting something which is not even asked. – Vinod Srivastav Apr 03 '23 at 12:33
  • @VinodSrivastav If you read carefully the question you will understand that the author is not sure how to do the conversion and just trying some libs, one of which is json.net. My answer is even better, because I say that it is not necessary to use any additional libs for that goal ;) – Termininja Apr 08 '23 at 11:05
  • @Termininja If you see the history the question is changed from the original which was **Convert JSON to XML or XML to JSON by using Json.NET** that's the reason it was tagged with `json.net` specifically and later he even answered it https://stackoverflow.com/a/816095/3057246 So the assumption **not sure.. trying some libs** is wrong. Although this can be an alternate answer if the first attempt was in context with `json.net` as here https://stackoverflow.com/a/814027/3057246 – Vinod Srivastav Apr 08 '23 at 21:08
  • @VinodSrivastav In same way you can see also the tag `c#` and *"I am not sure in the Json.NET framework"*, so the main idea of the author is to convert from JSON to XML and vice versa on C#. The usage of some additional libs is optional and the best way is to do it without such, so my answer should be the best. Otherwise, refer to some other request about this topic and you can vote for moving my answer there, I'll not argue about this. About the other answers, everyone helps with what he knows about the topic, and I think this is proved from my answer likes. – Termininja Apr 10 '23 at 08:37
37

I'm not sure there is point in such conversion (yes, many do it, but mostly to force a square peg through round hole) -- there is structural impedance mismatch, and conversion is lossy. So I would recommend against such format-to-format transformations.

But if you do it, first convert from json to object, then from object to xml (and vice versa for reverse direction). Doing direct transformation leads to ugly output, loss of information, or possibly both.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • 1
    Even though your answer got smashed, I'm glad it is here. I want to do the conversion and was considering skipping the c# middle objects, but now not so sure. I would need to generate c# objects based on the XSD otherwise and since it would be purely only for conversion purposes it seemed like a wasted layer (and effort). If you have examples or more detail of how it is lossy that would be great to see. – CRice Aug 01 '14 at 09:50
  • Don't know why this got downvoted. I am currently fixing a bunch of bugs relating to several XML <-> JSON transforming steps in a product we have. Most are down to the loss of numeric types when converting from JSON to XML. – rikkit Nov 03 '14 at 11:44
  • The hard truth, useful answer. – FailedUnitTest Jan 11 '16 at 16:14
  • @CRice Years too late, but having the transfer objects preserves the XML schema, to some extent. For example, [as brought up by Levitikon](https://stackoverflow.com/questions/814001/how-to-convert-json-to-xml-or-xml-to-json#comment12525727_814027), if you try to convert an XML document with a single element array, the JSON convert can't know that it's an array unless it's coming from a transfer object with an array type. – jpaugh Jul 05 '19 at 18:38
  • 1
    Newtonsoft.JSON's [XmlNodeConverter](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Converters_XmlNodeConverter.htm) has a [config option](https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Converters_XmlNodeConverter_WriteArrayAttribute.htm) to avoid this issue when transferring from JSON to XML back to JSON, but it can't catch cases where the original format is XML – jpaugh Jul 05 '19 at 18:38
  • I like your way of json to object to xml but to counter your point what is need of that, old system use a vendor who provides SOAP XML in response so current system designed according to that and now old vendor replaced with the new one who is providing data in JSON format , so instead of writing complete new application its better to change JSON to XML and use same old methods and stored procedures. Does it make sense ? – rahularyansharma Dec 17 '20 at 16:28
32

Thanks for David Brown's answer. In my case of JSON.Net 3.5, the convert methods are under the JsonConvert static class:

XmlNode myXmlNode = JsonConvert.DeserializeXmlNode(myJsonString); // is node not note
// or .DeserilizeXmlNode(myJsonString, "root"); // if myJsonString does not have a root
string jsonString = JsonConvert.SerializeXmlNode(myXmlNode);
Trisped
  • 5,705
  • 2
  • 45
  • 58
David.Chu.ca
  • 37,408
  • 63
  • 148
  • 190
  • 4
    If your data is an array then you need to do something like this: JsonConvert.DeserializeXmlNode("{\"Row\":" + json + "}", "root").ToXmlString() otherwise you will get a "XmlNodeConverter can only convert JSON that begins with an object." exception. – Mitchell Skurnik Feb 17 '15 at 01:11
  • Yes, and you cannot start with a number. JsonConvert.DeserializeXmlNode("{\"1Row\":" + json + "}", "root").ToXmlString() will fail – DaFi4 Jan 18 '16 at 15:26
  • the above answer and @mitchell comment help me .. thank – Ajay2707 Oct 05 '17 at 11:18
9

I searched for a long time to find alternative code to the accepted solution in the hopes of not using an external assembly/project. I came up with the following thanks to the source code of the DynamicJson project:

public XmlDocument JsonToXML(string json)
{
    XmlDocument doc = new XmlDocument();

    using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
    {
        XElement xml = XElement.Load(reader);
        doc.LoadXml(xml.ToString());
    }

    return doc;
}

Note: I wanted an XmlDocument rather than an XElement for xPath purposes. Also, this code obviously only goes from JSON to XML, there are various ways to do the opposite.

Termininja
  • 6,620
  • 12
  • 48
  • 49
yourbuddypal
  • 543
  • 6
  • 18
  • 2
    I needed to do this recently in a SQLCLR and couldn't take a dependency so I just bit the bullet and wrote this [json-to-xml conversion routine](https://gist.github.com/gfody/d7d450dc54a15e586d5b6ab9794073a4), it was surprisingly simple and only about 20 lines of code. – gordy May 24 '16 at 21:42
  • how to remove typr from xml? – cracker Aug 29 '16 at 09:34
6

Here is the full c# code to convert xml to json

public static class JSon
{
public static string XmlToJSON(string xml)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    return XmlToJSON(doc);
}
public static string XmlToJSON(XmlDocument xmlDoc)
{
    StringBuilder sbJSON = new StringBuilder();
    sbJSON.Append("{ ");
    XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
    sbJSON.Append("}");
    return sbJSON.ToString();
}

//  XmlToJSONnode:  Output an XmlElement, possibly as part of a higher array
private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
{
    if (showNodeName)
        sbJSON.Append("\"" + SafeJSON(node.Name) + "\": ");
    sbJSON.Append("{");
    // Build a sorted list of key-value pairs
    //  where   key is case-sensitive nodeName
    //          value is an ArrayList of string or XmlElement
    //  so that we know whether the nodeName is an array or not.
    SortedList<string, object> childNodeNames = new SortedList<string, object>();

    //  Add in all node attributes
    if (node.Attributes != null)
        foreach (XmlAttribute attr in node.Attributes)
            StoreChildNode(childNodeNames, attr.Name, attr.InnerText);

    //  Add in all nodes
    foreach (XmlNode cnode in node.ChildNodes)
    {
        if (cnode is XmlText)
            StoreChildNode(childNodeNames, "value", cnode.InnerText);
        else if (cnode is XmlElement)
            StoreChildNode(childNodeNames, cnode.Name, cnode);
    }

    // Now output all stored info
    foreach (string childname in childNodeNames.Keys)
    {
        List<object> alChild = (List<object>)childNodeNames[childname];
        if (alChild.Count == 1)
            OutputNode(childname, alChild[0], sbJSON, true);
        else
        {
            sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
            foreach (object Child in alChild)
                OutputNode(childname, Child, sbJSON, false);
            sbJSON.Remove(sbJSON.Length - 2, 2);
            sbJSON.Append(" ], ");
        }
    }
    sbJSON.Remove(sbJSON.Length - 2, 2);
    sbJSON.Append(" }");
}

//  StoreChildNode: Store data associated with each nodeName
//                  so that we know whether the nodeName is an array or not.
private static void StoreChildNode(SortedList<string, object> childNodeNames, string nodeName, object nodeValue)
{
    // Pre-process contraction of XmlElement-s
    if (nodeValue is XmlElement)
    {
        // Convert  <aa></aa> into "aa":null
        //          <aa>xx</aa> into "aa":"xx"
        XmlNode cnode = (XmlNode)nodeValue;
        if (cnode.Attributes.Count == 0)
        {
            XmlNodeList children = cnode.ChildNodes;
            if (children.Count == 0)
                nodeValue = null;
            else if (children.Count == 1 && (children[0] is XmlText))
                nodeValue = ((XmlText)(children[0])).InnerText;
        }
    }
    // Add nodeValue to ArrayList associated with each nodeName
    // If nodeName doesn't exist then add it
    List<object> ValuesAL;

    if (childNodeNames.ContainsKey(nodeName))
    {
        ValuesAL = (List<object>)childNodeNames[nodeName];
    }
    else
    {
        ValuesAL = new List<object>();
        childNodeNames[nodeName] = ValuesAL;
    }
    ValuesAL.Add(nodeValue);
}

private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
{
    if (alChild == null)
    {
        if (showNodeName)
            sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
        sbJSON.Append("null");
    }
    else if (alChild is string)
    {
        if (showNodeName)
            sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
        string sChild = (string)alChild;
        sChild = sChild.Trim();
        sbJSON.Append("\"" + SafeJSON(sChild) + "\"");
    }
    else
        XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
    sbJSON.Append(", ");
}

// Make a string safe for JSON
private static string SafeJSON(string sIn)
{
    StringBuilder sbOut = new StringBuilder(sIn.Length);
    foreach (char ch in sIn)
    {
        if (Char.IsControl(ch) || ch == '\'')
        {
            int ich = (int)ch;
            sbOut.Append(@"\u" + ich.ToString("x4"));
            continue;
        }
        else if (ch == '\"' || ch == '\\' || ch == '/')
        {
            sbOut.Append('\\');
        }
        sbOut.Append(ch);
    }
    return sbOut.ToString();
 }
}

To convert a given XML string to JSON, simply call XmlToJSON() function as below.

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

string json = JSON.XmlToJSON(xml);
// json = { "menu": {"id": "file", "popup": { "menuitem": [ {"onclick": "CreateNewDoc()", "value": "New" }, {"onclick": "OpenDoc()", "value": "Open" }, {"onclick": "CloseDoc()", "value": "Close" } ] }, "value": "File" }}
Nimesh khatri
  • 763
  • 12
  • 29
3

Here is a simple snippet that converts a XmlNode (recursively) into a hashtable, and groups multiple instances of the same child into an array (as an ArrayList). The Hashtable is usually accepted to convert into JSON by most of the JSON libraries.

protected object convert(XmlNode root){
    Hashtable obj = new Hashtable();
    for(int i=0,n=root.ChildNodes.Count;i<n;i++){
        object result = null;
        XmlNode current = root.ChildNodes.Item(i);

        if(current.NodeType != XmlNodeType.Text)
            result = convert(current);
        else{
            int resultInt;
            double resultFloat;
            bool resultBoolean;
            if(Int32.TryParse(current.Value, out resultInt)) return resultInt;
            if(Double.TryParse(current.Value, out resultFloat)) return resultFloat;
            if(Boolean.TryParse(current.Value, out resultBoolean)) return resultBoolean;
            return current.Value;
        }

        if(obj[current.Name] == null)
            obj[current.Name] = result;
        else if(obj[current.Name].GetType().Equals(typeof(ArrayList)))
            ((ArrayList)obj[current.Name]).Add(result);
        else{
            ArrayList collision = new ArrayList();
            collision.Add(obj[current.Name]);
            collision.Add(result);
            obj[current.Name] = collision;
        }
    }

    return obj;
}
3

Try this function. I just wrote it and haven't had much of a chance to test it, but my preliminary tests are promising.

public static XmlDocument JsonToXml(string json)
{
    XmlNode newNode = null;
    XmlNode appendToNode = null;
    XmlDocument returnXmlDoc = new XmlDocument();
    returnXmlDoc.LoadXml("<Document />");
    XmlNode rootNode = returnXmlDoc.SelectSingleNode("Document");
    appendToNode = rootNode;

    string[] arrElementData;
    string[] arrElements = json.Split('\r');
    foreach (string element in arrElements)
    {
        string processElement = element.Replace("\r", "").Replace("\n", "").Replace("\t", "").Trim();
        if ((processElement.IndexOf("}") > -1 || processElement.IndexOf("]") > -1) && appendToNode != rootNode)
        {
            appendToNode = appendToNode.ParentNode;
        }
        else if (processElement.IndexOf("[") > -1)
        {
            processElement = processElement.Replace(":", "").Replace("[", "").Replace("\"", "").Trim();
            newNode = returnXmlDoc.CreateElement(processElement);
            appendToNode.AppendChild(newNode);
            appendToNode = newNode;
        }
        else if (processElement.IndexOf("{") > -1 && processElement.IndexOf(":") > -1)
        {
            processElement = processElement.Replace(":", "").Replace("{", "").Replace("\"", "").Trim();
            newNode = returnXmlDoc.CreateElement(processElement);
            appendToNode.AppendChild(newNode);
            appendToNode = newNode;
        }
        else
        {
            if (processElement.IndexOf(":") > -1)
            {
                arrElementData = processElement.Replace(": \"", ":").Replace("\",", "").Replace("\"", "").Split(':');
                newNode = returnXmlDoc.CreateElement(arrElementData[0]);
                for (int i = 1; i < arrElementData.Length; i++)
                {
                    newNode.InnerText += arrElementData[i];
                }

                appendToNode.AppendChild(newNode);
            }
        }
    }

    return returnXmlDoc;
}
Termininja
  • 6,620
  • 12
  • 48
  • 49
3

For convert JSON string to XML try this:

    public string JsonToXML(string json)
    {
        XDocument xmlDoc = new XDocument(new XDeclaration("1.0", "utf-8", ""));
        XElement root = new XElement("Root");
        root.Name = "Result";

        var dataTable = JsonConvert.DeserializeObject<DataTable>(json);
        root.Add(
                 from row in dataTable.AsEnumerable()
                 select new XElement("Record",
                                     from column in dataTable.Columns.Cast<DataColumn>()
                                     select new XElement(column.ColumnName, row[column])
                                    )
               );


        xmlDoc.Add(root);
        return xmlDoc.ToString();
    }

For convert XML to JSON try this:

    public string XmlToJson(string xml)
    {
       XmlDocument doc = new XmlDocument();
       doc.LoadXml(xml);

       string jsonText = JsonConvert.SerializeXmlNode(doc);
       return jsonText;
     }
Hasan Fathi
  • 5,610
  • 4
  • 42
  • 60
  • Can you tell me why i cannot use `DeserializeXNode` as `XNode node = JsonConvert.DeserializeXNode(json, "Root")` directly cause in the other one you are using `SerializeXmlNode` ? – Vinod Srivastav Apr 03 '23 at 12:13
0

I did like David Brown said but I got the following exception.

$exception {"There are multiple root elements. Line , position ."} System.Xml.XmlException

One solution would be to modify the XML file with a root element but that is not always necessary and for an XML stream it might not be possible either. My solution below:

var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\App_Data"));
var directoryInfo = new DirectoryInfo(path);
var fileInfos = directoryInfo.GetFiles("*.xml");

foreach (var fileInfo in fileInfos)
{
    XmlDocument doc = new XmlDocument();
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ConformanceLevel = ConformanceLevel.Fragment;

    using (XmlReader reader = XmlReader.Create(fileInfo.FullName, settings))
    {
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                var node = doc.ReadNode(reader);
                string json = JsonConvert.SerializeXmlNode(node);
            }
        }
    }
}

Example XML that generates the error:

<parent>
    <child>
        Text
    </child>
</parent>
<parent>
    <child>
        <grandchild>
            Text
        </grandchild>
        <grandchild>
            Text
        </grandchild>
    </child>
    <child>
        Text
    </child>
</parent>
Ogglas
  • 62,132
  • 37
  • 328
  • 418
-1

I have used the below methods to convert the JSON to XML

List <Item> items;
public void LoadJsonAndReadToXML() {
  using(StreamReader r = new StreamReader(@ "E:\Json\overiddenhotelranks.json")) {
    string json = r.ReadToEnd();
    items = JsonConvert.DeserializeObject <List<Item>> (json);
    ReadToXML();
  }
}

And

public void ReadToXML() {
  try {
    var xEle = new XElement("Items",
      from item in items select new XElement("Item",
        new XElement("mhid", item.mhid),
        new XElement("hotelName", item.hotelName),
        new XElement("destination", item.destination),
        new XElement("destinationID", item.destinationID),
        new XElement("rank", item.rank),
        new XElement("toDisplayOnFod", item.toDisplayOnFod),
        new XElement("comment", item.comment),
        new XElement("Destinationcode", item.Destinationcode),
        new XElement("LoadDate", item.LoadDate)
      ));

    xEle.Save("E:\\employees.xml");
    Console.WriteLine("Converted to XML");
  } catch (Exception ex) {
    Console.WriteLine(ex.Message);
  }
  Console.ReadLine();
}

I have used the class named Item to represent the elements

public class Item {
  public int mhid { get; set; }
  public string hotelName { get; set; }
  public string destination { get; set; }
  public int destinationID { get; set; }
  public int rank { get; set; }
  public int toDisplayOnFod { get; set; }
  public string comment { get; set; }
  public string Destinationcode { get; set; }
  public string LoadDate { get; set; }
}

It works....

Mickael Lherminez
  • 679
  • 1
  • 10
  • 29
  • Hi if you read the question it is tagged with `Json.NET` and as king how to do it with `Json.NET` not *How to do without `Json.NET`*. If you understand this please update your answer using `Json.NET` – Vinod Srivastav Apr 03 '23 at 12:15