killer
killer

Reputation: 121

Create XML element with attributes C# has extra xmls=""

Following is my requirement. I am reading an xml file (*.csproj file) and searching for a node in it. After I find the node I will insert my element into it. Following is my original XML:

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

Following is my code snippet to do this.

        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(inputFile);

        XmlNamespaceManager nsMgr = new XmlNamespaceManager(xDoc.NameTable);
        string strNamespace = xDoc.DocumentElement.NamespaceURI;
        nsMgr.AddNamespace("ns", strNamespace);
        XmlNode root = xDoc.SelectSingleNode("/ns:Project/ns:ItemGroup/ns:ClInclude", nsMgr);

        XmlAttribute attr = xDoc.CreateAttribute("Include");
        attr.Value = "NewHeaderFile.h";

        XmlElement xele = xDoc.CreateElement("ClInclude");
        xele.Attributes.Append(attr);

        root.ParentNode.AppendChild(xele);
        xDoc.Save(outFile);

This is the output what i get.

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

Problem Statement: I want to ignore the xmlns="" in my output. My output should look like this.

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

Kinldy help me. Thanks for your valuable time.

Upvotes: 3

Views: 345

Answers (2)

invernomuto
invernomuto

Reputation: 10211

Change your element declaration with following and should work

XmlElement xele = xDoc.CreateElement("ClInclude", xDoc.DocumentElement.NamespaceURI);

Add the namespace on root mean that your element are in the 'root' namespace, so there is no need to add a 'no namespace' to new element

Upvotes: 4

StuartLC
StuartLC

Reputation: 107277

All elements in the original document are in namespace xmlns="http://schemas.microsoft.com/developer/msbuild/2003", whereas you are creating the new ClInclude element in the empty namespace "". If you also create this element in xmlns="http://schemas.microsoft.com/developer/msbuild/2003", the extraneous xmlns="" will be omitted from the output xml.

Upvotes: 3

Related Questions