Ignore namespace attributes while serializing xml data to json

381 Views Asked by At

I am trying to serialize xml directly to json using JsonSerializer() but the namespace attributes are getting added as fields in the final json. Any suggestion on how to remove this? I tried with JsonConvert.Serialize() but some childnodes are missing in the serialized json.

1

There are 1 best solutions below

2
On

A solution to your problem could be to deserialize your object to a dictionary first. This way you can add some logic in between the conversion to it.

Check the example below:

            var xml = @"<?xml version='1.0' standalone='no'?>
            <root>
              <person id='1'>
                <name>Alan</name>
                <url>http://www.google.com</url>
              </person>
              <person id='2'>
                <name>Louis</name>
                <url>http://www.yahoo.com</url>
              </person>
            </root>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            var childNodeList = doc.DocumentElement.ChildNodes;

            for (int i = 0; i < childNodeList.Count; i++)
            {
                var nodes = childNodeList.Item(i).ChildNodes;

                var dict = new Dictionary<string, object>();

                foreach (XmlNode node in nodes)
                {
                    var serializedNode = JsonConvert.SerializeXmlNode(node);

                    var prop = JsonConvert.DeserializeObject<IDictionary<string, object>>(serializedNode).FirstOrDefault();

                    dict.Add(prop.Key, prop.Value ?? " ");
                }

                Console.WriteLine($"item {i}");
                Console.WriteLine(string.Join("\r\n", dict.Select(e => $"{e.Key}: {e.Value}")));
            }

Output:

     //item 0
     //name: Alan
     //url: http://www.google.com
     //item 1
     //name: Louis
     //url: http://www.yahoo.com