0

I have 2 xelement which I want to merge :

The first one is like this :

<element xmlns="test1">
    <child>element child</child>
</element>

The second one is like this :

<element2>
    <child2>element2 child2</child2>
</element2>

I would like to obtain the following :

<root xmlns="fusion">   
    <element xmlns="test1">
        <child>element child</child>
    </element>
    <element2>
        <child2>element2 child2</child2>
    </element2>
</root> 

The problem is that when I try to merge the 2 xelement in my root node, it automatically add an empty xmlns attribute to my second element which I don't want :

<root xmlns="fusion">   
    <element xmlns="test1">
        <child>element child</child>
    </element>
    <element2 xmlns="">
        <child2>element2 child2</child2>
    </element2>
</root> 

This is my code :

        XNamespace defaultNs = "fusion";
        var root = new XElement(defaultNs + "root");

        root.Add(element);
        root.Add(element2); //when I debug and visualize my element2 I don't have this empty xmlns attribute, it's only when I do the fusion that it appears
user2443476
  • 1,935
  • 9
  • 37
  • 66

1 Answers1

0

xmlns defines an XML Namespace. It will not cause any problem in your appliction logic.

The web segguset a number of possabilites:

1

You're adding an element with namespace "" to an element with namespace "http://schemas.microsoft.com/developer/msbuild/2003". This means that the new element needs an xmlns attribute.

If you add an element with namespace "http://schemas.microsoft.com/developer/msbuild/2003", no xmlns attribute is needed (because it's inherited from the parent element):

var n = xDoc.CreateNode(XmlNodeType.Element, "Compile",
            "http://schemas.microsoft.com/developer/msbuild/2003");

2

From here

foreach (XElement e in root.DescendantsAndSelf())
{
    if (e.Name.Namespace == string.Empty)
    {
        e.Name = ns + e.Name.LocalName;
    }
}

3

From here ,Based on interface:

string RemoveAllNamespaces(string xmlDocument);

I represent here final clean and universal C# solution for removing XML namespaces:

//Implemented based on interface, not part of algorithm
public static string RemoveAllNamespaces(string xmlDocument)
{
    XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));

    return xmlDocumentWithoutNs.ToString();
}

//Core recursion function
 private static XElement RemoveAllNamespaces(XElement xmlDocument)
    {
        if (!xmlDocument.HasElements)
        {
            XElement xElement = new XElement(xmlDocument.Name.LocalName);
            xElement.Value = xmlDocument.Value;

            foreach (XAttribute attribute in xmlDocument.Attributes())
                xElement.Add(attribute);

            return xElement;
        }
        return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
    }
Community
  • 1
  • 1
Yael
  • 1,566
  • 3
  • 18
  • 25