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