Home > Mobile >  XML to Json without array name c#
XML to Json without array name c#

Time:08-25

I have following xml file

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <UserData>
      <User_Email>[email protected]</User_Email>
      <User_Name>Louis Hebert</User_Name>
      <User_State>South Dakota</User_State>
      <id>item1</id>
   </UserData>
   <UserData>
      <User_Email>[email protected]</User_Email>
      <User_Name>David Lewis</User_Name>
      <User_State>Connecticut</User_State>
      <id>item2</id>
   </UserData>
</root>

After converting to json the result is something like

{
  "UserData": [
    {
      "User_Email": "[email protected]",
      "User_Name": "Louis Hebert",
      "User_State": "South Dakota",
      "id": "item1"
    },
    {
      "User_Email": "[email protected]",
      "User_Name": "David Lewis",
      "User_State": "Connecticut",
      "id": "item2"
    }
    ]
}

C# code which i am using

XmlDocument xmldoc = new XmlDocument();
            string xml1 = @"D:\Visual_Codes\Xml_Files\Data.xml";
            xmldoc.Load(xml1);
            xmldoc.RemoveChild(xmldoc.FirstChild);
            string js = JsonConvert.SerializeXmlNode(xmldoc, Newtonsoft.Json.Formatting.Indented, true);

Required Output

[
        {
          "User_Email": "[email protected]",
          "User_Name": "Louis Hebert",
          "User_State": "South Dakota",
          "id": "item1"
        },
        {
          "User_Email": "[email protected]",
          "User_Name": "David Lewis",
          "User_State": "Connecticut",
          "id": "item2"
        }
        ]

Summarising question Required a json file without array name after converting from xml to json

CodePudding user response:

Just parse your json and select the part you want

var js = JObject.Parse(JsonConvert.SerializeXmlNode(xmldoc))["root"]["UserData"]
                                                            .ToString();

CodePudding user response:

You can serialize each of the elements on its own and add the overhead by hand. If the structure won't change, this should be enough.

        XmlDocument xmldoc = new XmlDocument();
        string xml1 = @"path\sample.xml";
        xmldoc.Load(xml1);

        XmlNode root = xmldoc.DocumentElement;
        var elements = root.ChildNodes;

        string js = "{\n[\n";

        for(int i = 0; i < elements.Count; i  )
        {
            if (i != 0)
                js  = ",\n";

            js  = JsonConvert.SerializeXmlNode(elements[0], Newtonsoft.Json.Formatting.Indented, true);
        }

        js  = "\n]\n}";

CodePudding user response:

JsonConvert.SerializeXmlNode() will never return an array as the root JSON container because, as explained in Converting between JSON and XML, since XML does not have the concept of an array, Json.NET maps repeating XML elements of the same name to a JSON array. Thus your desired JSON could only be created from XML with repeating root elements like so:

<UserData>
   <User_Email>[email protected]</User_Email>
   <User_Name>Louis Hebert</User_Name>
   <User_State>South Dakota</User_State>
   <id>item1</id>
</UserData>
<UserData>
   <User_Email>[email protected]</User_Email>
   <User_Name>David Lewis</User_Name>
   <User_State>Connecticut</User_State>
   <id>item2</id>
</UserData>

However, as a well-formed XML document must have one and only one root element, there is no way for this conversion to result from any well-formed XML document.

Instead, you will need to postprocess your JSON to get the required JSON array. This can be done as follows. First, create the following extension method to convert directly from an XmlNode to a JToken:

public static partial class JsonExtensions
{
    public static JToken ToJToken(this XmlNode node, bool omitRootObject = false, string deserializeRootElementName = null, bool writeArrayAttribute = false) =>
        JToken.FromObject(node, JsonSerializer.CreateDefault(
            new JsonSerializerSettings { Converters = { new XmlNodeConverter { OmitRootObject = omitRootObject, DeserializeRootElementName = deserializeRootElementName, WriteArrayAttribute = writeArrayAttribute } } }
        ));
}

Now you will be able to do:

var root = (JObject)xmldoc.DocumentElement.ToJToken(omitRootObject : true);
var array = root.PropertyValues().SingleOrDefault();
string js = array.ToString();

Demo fiddle here.

  • Related