Skip to content

Instantly share code, notes, and snippets.

@sidneyspe
Created May 3, 2023 18:34
Show Gist options
  • Select an option

  • Save sidneyspe/877a1d4398bf97f35ebd433ee8e9da39 to your computer and use it in GitHub Desktop.

Select an option

Save sidneyspe/877a1d4398bf97f35ebd433ee8e9da39 to your computer and use it in GitHub Desktop.
Handle XML using cshap
using System;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text.Json;
class Program
{
static void Main(string[] args)
{
// Carrega o arquivo XML em um objeto XDocument
XDocument doc = XDocument.Load("caminho/para/arquivo.xml");
// Converte o objeto XDocument em um objeto dinâmico recursivamente
dynamic xmlObj = ConvertXElementToDynamic(doc.Root);
// Converte o objeto dinâmico em JSON
string json = JsonSerializer.Serialize(xmlObj);
// Imprime o JSON resultante
Console.WriteLine(json);
}
static dynamic ConvertXElementToDynamic(XElement element)
{
// Cria um objeto dinâmico para o elemento atual
IDictionary<string, object> expando = new ExpandoObject();
foreach (var attribute in element.Attributes())
{
expando[attribute.Name.LocalName] = attribute.Value.Trim();
}
// Adiciona os filhos do elemento atual ao objeto dinâmico de forma recursiva
var childElements = element.Elements().ToList();
if (childElements.Count > 0)
{
IDictionary<string, object> childExpando = new ExpandoObject();
foreach (var childElement in childElements)
{
var childExpandoElement = ConvertXElementToDynamic(childElement);
if (childExpando.ContainsKey(childElement.Name.LocalName))
{
// Se o elemento já existe, converte para uma lista e adiciona o novo elemento
if (childExpando[childElement.Name.LocalName] is List<dynamic>)
{
((List<dynamic>)childExpando[childElement.Name.LocalName]).Add(childExpandoElement);
}
else
{
var existingElement = childExpando[childElement.Name.LocalName];
childExpando[childElement.Name.LocalName] = new List<dynamic> { existingElement, childExpandoElement };
}
}
else
{
// Se o elemento não existe, adiciona ao objeto dinâmico
childExpando[childElement.Name.LocalName] = childExpandoElement;
}
}
// Adiciona o objeto dinâmico dos filhos ao objeto dinâmico atual
foreach (var item in childExpando)
{
expando[item.Key] = item.Value;
}
}
else
{
// Se o elemento não tem filhos, adiciona seu valor ao objeto dinâmico atual
if (!element.IsEmpty)
{
expando["_text"] = element.Value.Trim();
}
}
return expando;
}
}
@sidneyspe
Copy link
Copy Markdown
Author

using System;
using System.Xml.Linq;
using Newtonsoft.Json;

public class Program
{
public static void Main()
{
var xml = @"

<title>The Title</title>
The Author
The Publisher

Category 1
Category 2
Category 3



<title>Chapter 1 Title</title>
Chapter 1 Content


<title>Chapter 2 Title</title>
Chapter 2 Content


";

    var json = ConvertXmlToJson(xml);
    Console.WriteLine(json);
}

public static string ConvertXmlToJson(string xml)
{
    var root = XElement.Parse(xml);
    var json = new JObject();
    foreach (var element in root.Elements())
    {
        if (element.HasElements)
        {
            json[element.Name.LocalName] = CreateJArray(element.Elements());
        }
        else
        {
            json[element.Name.LocalName] = element.Value;
        }

        foreach (var attribute in element.Attributes())
        {
            json[element.Name.LocalName + "_" + attribute.Name.LocalName] = attribute.Value;
        }
    }

    return json.ToString();
}

private static JArray CreateJArray(IEnumerable<XElement> elements)
{
    var jArray = new JArray();
    foreach (var element in elements)
    {
        var jObject = new JObject();
        foreach (var child in element.Elements())
        {
            if (child.HasElements)
            {
                jObject[child.Name.LocalName] = CreateJArray(child.Elements());
            }
            else
            {
                jObject[child.Name.LocalName] = child.Value;
            }

            foreach (var attribute in child.Attributes())
            {
                jObject[child.Name.LocalName + "_" + attribute.Name.LocalName] = attribute.Value;
            }
        }
        jArray.Add(jObject);
    }

    return jArray;
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment