Thursday, 11 December 2014

Create XML element with attributes C#



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://ift.tt/PiGwmX">
<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://ift.tt/PiGwmX">
<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://ift.tt/PiGwmX">
<ItemGroup>
<ClInclude Include="Stdafx.h" />
<ClInclude Include="NewFile.h" />
<ClInclude Include="NewHeaderFile.h" />
</ItemGroup>
</Project>


Kinldy help me. Thanks for your valuable time.


No comments:

Post a Comment