2016-10-17 124 views
0

我想爲我的根元素(一個默認和一個命名)創建一個帶有兩個命名空間的XML文件。以下是我的代碼:XML添加了命名空間和默認命名空間錯誤

var testdoc= new XDocument(
     new XDeclaration("1.0", "utf-8", "yes"), 
     new XElement("Document", 
      new XAttribute("xmlns", "namespace1"), 
      new XAttribute(XNamespace.Xmlns + "xsi", "namespace2"), 
      new XElement("sampleElem", "content") 
     ) 
); 

這會產生以下錯誤:

the prefix for "namespace2" can not be redefined within the same code for starting a new element.

我理解錯誤,但我不明白爲什麼我把它(爲前綴的名字是不一樣的)。任何人都知道獲得理想結果的正確方法嗎?

回答

1

因爲在這一行new XElement("Document",您已經創建了一個默認名稱空間的元素。指定您嘗試覆蓋它的屬性。

做這個

XNamespace ns = "namespace1"; 

var testdoc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"), 
    new XElement(ns + "Document", 
     new XAttribute(XNamespace.Xmlns + "xsi", "namespace2"), 
     new XElement("sampleElem", "content") 
    ) 
);