我有一個XML文件,我需要在運行時將名稱空間應用於該文件。我搜索了網絡,大多數例子似乎都建議使用「SetAttributeValue」函數。當我使用下面的代碼時,它會拋出一個異常,當我嘗試「ToString()」時出現以下錯誤:無法在運行時將名稱空間添加到XML
The prefix '' cannot be redefined from '' to 'http://schemas.datacontract.org/2004/07/' within the same start element tag.
任何想法發生了什麼問題?
XDocument data = XDocument.Parse("<Root><Stuff>Test</Stuff></Root>");
string ns = "http://schemas.datacontract.org/2004/07/";
data.Root.SetAttributeValue("xmlns",ns);
SaveFile(data.ToString());