为什么每次我尝试向节点添加新属性时,都会添加额外的属性"xmlns="
?有什么方法可以阻止这种情况吗?
public void changeProjToAssembly(string projPath,string projRefName)
{
XmlDocument doc = new XmlDocument();
doc.Load(projPath);
XmlNode projectReferenceNode;
XmlNode itemGroupNode;
XmlNode root = doc.DocumentElement;
string s = doc.DocumentElement.GetNamespaceOfPrefix("");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("rs", s);
projectReferenceNode = root.SelectSingleNode("/rs:Project/rs:ItemGroup/rs:ProjectReference[rs:Name='GS_POSLibrary1']", nsmgr);
itemGroupNode = root.SelectSingleNode("/rs:Project/rs:ItemGroup[rs:ProjectReference/rs:Name='GS_POSLibrary1']", nsmgr);
XmlElement newCd = doc.CreateElement("Reference");
newCd.SetAttribute("Include", "dasdsad");
newCd.InnerXml = "<HintPath>" + ".//sadssa/asdsad" + "</HintPath>"+
"<HintPath>" + ".//sadssa/asdsad" + "</HintPath>" +
"<HintPath>" + ".//sadssa/asdsad" + "</HintPath>";
itemGroupNode.ReplaceChild(newCd, projectReferenceNode);
Console.WriteLine("Display the modified XML document....");
doc.Save(Console.Out);
}
XML:
<ItemGroup>
<ProjectReference Include="..\common\librarycomponents\exportdb\GenerateDocLibrary.vbproj">
<Project>{9B3C9E8B-436B-4A16-87A8-E72CB2FFC6E6}</Project>
<Name>GS_POSLibrary</Name>
<Private>False</Private>
</ProjectReference>
<Reference Include="dasdsad" xmlns="">//I only need the Include Atrribute
<HintPath>.//sadssa/asdsad</HintPath>
<HintPath>.//sadssa/asdsad</HintPath>
<HintPath>.//sadssa/asdsad</HintPath>
</Reference>
答案 0 :(得分:2)
您在空命名空间中创建了Reference
元素,而不是在rs
命名空间中。尝试使用doc.CreateElement("Reference", s);
答案 1 :(得分:0)
我认为这是因为您在此处向文档中添加了一个空命名空间:
string s = doc.DocumentElement.GetNamespaceOfPrefix("");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("rs", s);
然后当你附加那个节点时,它会附加你添加的命名空间。