Category Archives: XML documents

Adding an XML element without namespace (xmlns) attribute

Issue:
When adding creating an element in an XmlDocment an unwanted namespace attribute may appears in your xml file.
You have to be carefull to add the new element in the correct namespace.
That does not always have to be the NamespaceURI of the document, but must be the NamespaceURI of the parent node.

Example:
This is an example of a SandCastle project file.
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
...
</Project>

I want to add a element called ItemGroup with a certain attribute inside.
My first try was to write this code:

XmlNode project = xmlDoc.GetElementsByTagName("Project")[0];
XmlNode newItemGroup = project.AppendChild(xmlDoc.CreateElement("ItemGroup", null));
newItemGroup.InnerXml = "<Folder Include="MyFolder"/>";

But this resulted in an undesired xml.file that could not be handled by the parser (in this case MsBuild or Sandcastle Help File Builder)

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<ItemGroup xmlns="">
<Folder Include="MyFolder" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" />
</ItemGroup>
</Project>

Note: The xmlns text that was added. This caused the issue.

Solution:

The solution is to create the new element in the same namespace as it’s parent node.
In other words, the element must be created with the namespace of the node.

This is the working code that uses the NamespaceURI property of the project node.:

XmlNode project = xmlDoc.GetElementsByTagName("Project")[0];
XmlNode newItemGroup = project.AppendChild(xmlDoc.CreateElement("ItemGroup", project.NamespaceURI));
newItemGroup.InnerXml = "";

This will results in this Xml file:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<ItemGroup>
<Folder Include="MyFolder" />
</ItemGroup>
</Project>