Skip to content

JsonConvert.SerializeXNode: Global namespace on child nodes are lost and implicitly replaced with parent elements namespace #2681

@tkvalvik

Description

@tkvalvik

Empty namespaces are lost during serialization if parent-element has a non-empty namespace.

Source/destination types

var xml = new XElement("{x}a", new XElement("b", ""));
var json = JsonConvert.SerializeXNode(xml);
Console.WriteLine(json); 

Source/destination JSON

{
  "a": {
    "@xmlns": "x",
    "b": ""
  }
}

Expected behavior

xmlns should be present on an element when it differs from its parent, even when it is the global namespace.

{
  "a": {
    "@xmlns": "x",
    "b": {
      "@xmlns": ""
    }
  }
}

Actual behavior

No xmlns-attribute on the b-element, even though its namespace differs its parent.

This also means that empty namespaces are dropped in a serialize/deserialize round trip.

Steps to reproduce

var xml = new XElement("{x}a", new XElement("b", ""));
Console.WriteLine($"Before: \n:{xml}"); 
var json = JsonConvert.SerializeXNode(xml);
var deserializedXml = JsonConvert.DeserializeXNode(json);
Console.WriteLine($"After: \n:{deserializedXml}");

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions