web analytics

How to remove Unneeded xmlns Attribute?

Options

codeling 1602 - 6666
@2017-04-24 16:21:54

By default, when you add child elements to a parent node with NamespacUri,  the attribute xmlns ="" is added to the child name. This problem usually occurs because the required xmlDocument.CreateElement overload taking a namespace URI is not used. The namespace of an element node is determined when you create it thus if you want to create an add element in a certain namespace (e.g. http://example.com/2007/ns1) then you need to pass that namespace to an overload of CreateElement that takes a namespace URI e.g.

XmlElement addElement = xmlDocumentInstance.CreateElement("add", "http://example.com/2007/ns1");

That way you create an add element in that particular namespace.

If you simply do

XmlElement addElement = xmlDocumentInstance.CreateElement("add");

then you create an add element in no namespace. Consequently when you later insert that element to a parent node that is in a namespace and then serialize the changed document the serializer adds xmlns="" as the add element is in no namespace.

So decide which namespace your elements are supposed to have and pass that namespace URI to CreateElement each time you create an element, then the problem of xmlns="" goes away. For instance assuming you know the new parent node of your element to append to you and you want the new element to have the same namespace then you can simply do e.g.

XmlElement addElement = xmlDocumentInstance.CreateElement("add", newParentNode.NamespaceURI);

addElement.SetAttribute("key", "MyKey");

// .. set further attributes as needed

newParentNode.AppendChild(addElement);

 

 

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com