1

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. I am able to serialize xml to json. What i am concerned about is the namespaces. They needs to be removed. If you take a look at the documentation you shared, in conversion rules, you can see that attributes are converted with @ infront. I dont need them at all. Also are you familiar with any way to substitute null values with empty spaces? Nullvaluehandling.ignore is not working
@TimLeslie I've updated my answer. I Hope this will help you out!

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.