2010-11-16 98 views
1

为什么每次我尝试向节点添加新属性时,它都会添加一个额外的属性"xmlns="?任何方式来防止这种情况?xml文档,设置属性问题

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> 

+2

也许你可以显示你的代码?你如何期待我们知道为什么你的代码添加了'xmlns'属性而不显示你的代码,即使我们有线索?似乎与我矛盾。 – 2010-11-16 19:02:43

+0

对不起,我现在已经添加了代码,我试图通过直接编辑它的xml内容来编辑vbproj文件中的项目引用,作为程序集引用进行更改 – 3ggerhappy 2010-11-16 19:08:50

+0

请显示生成的XML。另外,请说明你为什么关心xmlns属性。 – 2010-11-16 19:18:44

回答

2

您在空命名空间创建了Reference元素,而不是在rs命名空间。尝试使用doc.CreateElement("Reference", s);

+0

Omg它的工作,非常感谢,xmlns属性消失 – 3ggerhappy 2010-11-16 20:07:53

+1

@ 3ggerhappy,我刚刚回答了一个非常类似的问题,在http://stackoverflow.com/questions/4189348/how-can-i-prevent-appendchild-from -adding-the-xmlns/4189693#4189693并解释了它为什么会发生这种情况。对命名空间的一点了解将有助于您避免将来出现这些误解。 – LarsH 2010-11-16 20:52:06

0

我想这是因为你要添加一个空的命名空间到这里的文件:

string s = doc.DocumentElement.GetNamespaceOfPrefix(""); 
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); 
nsmgr.AddNamespace("rs", s); 

然后当你追加它与自己添加的命名空间追加该节点。

+0

-1:对不起,那不是。 – 2010-11-16 19:38:53

+0

你在乎你解释为什么不是这样吗? – msarchet 2010-11-16 19:39:37

+0

我做了,在我的答案。 – 2010-11-17 00:30:59