2

As part of dynamic documents proccesor app we must migrate thousands of documents from XML to Json. This is my approach.

I have this Xml

<?xml version="1.0"?>
    <syscur_historial_schema>
        <strtipoobj>OM_SECCION</strtipoobj>
        <strnombreobj>_1_Seccion_IDENTIFICACION_DEL_PACIENTE</strnombreobj>
        <numobj>0.00</numobj>
        <txtpropsobj/>
        <txtprostit><![CDATA[BackColor = 14171687,BorderStyle = 0,FontBold = .F.,FontItalic = .F.,FontName = "Tahoma",FontSize = 9,FontUnderline = .F.,ForeColor = 0,AutoSize = .F.,BackStyle = 1,LineColor = 14171687, TitleWidth=100, CAPTION="IDENTIFICACION DEL PACIENTE"]]>
        </txtprostit>
        <strencabezado>IDENTIFICACION DEL PACIENTE</strencabezado>
    </syscur_historial_schema>

I converted it to JSon:

enter image description here

Then I need to deserialize that JSon into this c# class:

public class syscur_historial_schema
{
    public string strtipoobj { get; set; }
    public string strnombreobj { get; set; }
    public string numobj { get; set; }
    public string txtpropsobj { get; set; }
    public string txtprostit { get; set; }
    public string strencabezado { get; set; }
}

This is my Converter:

public class ConvertXmlToJson
{
    /// <summary>
    /// Convierte un archivo con formato XML en fornato JSon 
    /// usando JsonConvert.SerializeXmlNode(doc)
    /// </summary>
    /// <param name="xmlPath"></param>
    /// <returns></returns>
    public static string XmlToJsonSerializeXmlNode<T>(string xmlPath, string nodeName, bool cleanString)
    {
        string justPath = Path.GetDirectoryName(xmlPath);
        string json = Path.Combine(justPath, $"{Path.GetFileNameWithoutExtension(xmlPath)}.json");
        XmlDocument doc = new XmlDocument();

        if (cleanString)
            doc.LoadXml(CleanRepeatedSpaces(File.ReadAllText(xmlPath)));
        else
            doc.LoadXml(File.ReadAllText(xmlPath));

        XmlNodeList nodes = GetNode(doc, nodeName);
        List<T> lista = new List<T>();
        foreach (XmlNode node in nodes)
        {
            string jSonNode = JsonConvert.SerializeXmlNode(node);
            T obj = JsonConvert.DeserializeObject<T>(jSonNode);
            lista.Add(obj);
        }
        File.WriteAllText(json, JsonConvert.SerializeObject(lista));
        return json;
    }

    public static XmlNodeList GetNode(XmlDocument doc, string nodeName)
    {
        XmlNodeList nodes = doc.GetElementsByTagName(nodeName);
        return nodes;
    }
}    

And this test Method

[TestMethod]
public void Tools_ConvertXmlToJson_Tests()
{
    string path = "D:\\MyXmlPath\\";
    string xml = Path.Combine(path, "MyXmlFile.hist");
    string jsonFile = ConvertXmlToJson.XmlToJsonSerializeXmlNode<syscur_historial_schema>(xml, "syscur_historial_schema",true);
    Assert.AreEqual(true, File.Exists(jsonFile));
    List<syscur_historial_schema> jsonObject = JsonConvert.DeserializeObject<List<syscur_historial_schema>>(File.ReadAllText(jsonFile));
}

Now my problem is my Deserialized object always return null on every property, I was thinking the problem is CDATA node.

Questions

1- What I'm doing wrong ?

2- How to convert xml CDATA to Json string ?

2
  • 4
    Why are you going from XML to JSON and then to a C# object? Why not just deserialize the XML into a class? It would probably handle that CData section just fine. Commented Jul 5, 2018 at 18:38
  • @JLRishe I must convert a lot of files from xml to json as part of migration plan. And My XML schema is very old. I don't need to convert full xml. just some nodes from it. Commented Jul 5, 2018 at 18:53

1 Answer 1

4

Make your syscur_historial_schema class serialized like this:

[Serializeable]     
public class syscur_historial_schema
{
 public string strtipoobj { get; set; }
 public string strnombreobj { get; set; }
 public string numobj { get; set; }
 public string txtpropsobj { get; set; }
 public string txtprostit { get; set; }
 public string strencabezado { get; set; }
}

Then deserialize the xml into the class like this:

XmlSerializer serializer = new XmlSerializer(typeof(syscur_historial_schema));

StreamReader reader = new StreamReader(xmlPath);
var schema = (syscur_historial_schema)serializer.Deserialize(reader);
reader.Close();

Then convert schema into json like this:

 string json = JsonConverter.SerializeObject(schema);

You don't have to convert the xml string into an xml document prior to converting it to a class object. Straight deserialize the xml string directly into the class object.

Sign up to request clarification or add additional context in comments.

6 Comments

Tks for your approach. What is the NS for Serializeable property ?
It's an attribute...no namespace. Above the class declaration, just start typing "[" and it should appear with intellisense.
@dickrichie Well...it's technically in the System namespace.
@dickrichie Yep. you have a Typo at [Serializeable] must be [Serializable]
Ha! I'm a bad speller. Thank the gods for intellisense and google!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.