3

I have following xml file

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <UserData>
      <User_Email>cynthia48@example.com</User_Email>
      <User_Name>Louis Hebert</User_Name>
      <User_State>South Dakota</User_State>
      <id>item1</id>
   </UserData>
   <UserData>
      <User_Email>brian52@example.com</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": "cynthia48@example.com",
      "User_Name": "Louis Hebert",
      "User_State": "South Dakota",
      "id": "item1"
    },
    {
      "User_Email": "brian52@example.com",
      "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": "cynthia48@example.com",
          "User_Name": "Louis Hebert",
          "User_State": "South Dakota",
          "id": "item1"
        },
        {
          "User_Email": "brian52@example.com",
          "User_Name": "David Lewis",
          "User_State": "Connecticut",
          "id": "item2"
        }
        ]

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

Ayan Ahmed
  • 31
  • 2

3 Answers3

3

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>cynthia48@example.com</User_Email>
   <User_Name>Louis Hebert</User_Name>
   <User_State>South Dakota</User_State>
   <id>item1</id>
</UserData>
<UserData>
   <User_Email>brian52@example.com</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.

dbc
  • 104,963
  • 20
  • 228
  • 340
2

Just parse your json and select the part you want

var js = JObject.Parse(JsonConvert.SerializeXmlNode(xmldoc))["root"]["UserData"]
                                                            .ToString();
Serge
  • 40,935
  • 4
  • 18
  • 45
1

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}";
Revox
  • 61
  • 1
  • 4