2012-11-15 36 views
1

我已經嘗試將默認名稱空間添加到根,儘管它也將名稱空間添加到它的子節點。我想將名稱空間添加到現有的XDocument。不需要的名稱空間屬性添加到根子元素

我的代碼嘗試;

// add default namespace - attempt 1 
XNamespace xmlns = "http://www.myschema/schema.xsd"; 
xDocument.Root.Name = xmlns + xDocument.Root.Name.LocalName; 

// add default namespace - attempt 2 
XNamespace MyNS = "http://www.myschema/schema.xsd"; 
xDocument.Element("testFile").Name = MyNS.GetName("testFile"); 

XML;

<testFile version="1" xmlns="http://www.myschema/schema.xsd"> 
    <testResults xmlns=""> <!-- *** Unwanted Attribute *** --> 
    <result resultID="abcdefgh" comment="blah blah blah blah"> 
    </testResults> 
</testFile> 

我想知道爲什麼testResults有一個xmlns命名空間屬性連接到它?

這裏是一些測試C#代碼來測試;

XDocument xDocument = new XDocument(
    new XElement("testFile", 
     new XAttribute("version", "1"), 
     new XElement("testResults", 
      new XElement("result", 
       new XAttribute("resultID", "abcdefgh"), 
       new XAttribute("comment", "blah blah blah blah") 
     )))); 
+1

顯示創建其他元素的代碼。答案應該是顯而易見的。 –

+0

增加了一些測試代碼,我可以重現這一點。 – wonea

+0

[無法在運行時將名稱空間添加到XML](http://stackoverflow.com/questions/1607815/cant-add-namespace-to-xml-at-runtime) – andlrc

回答

1

下面的代碼:

var xDocument = new XmlDocument(); 
var element1 = xDocument.CreateElement("testFile", "http://www.myschema/schema.xsd"); 
element1.SetAttribute("version", "1"); 
xDocument.AppendChild(element1); 

var element2 = xDocument.CreateElement("testResults", "http://www.myschema/schema.xsd"); 
element1.AppendChild(element2); 

var element3 = xDocument.CreateElement("result", "http://www.myschema/schema.xsd"); 
element3.SetAttribute("resultID", "abcdefgh"); 
element3.SetAttribute("comment", "blah blah blah blah"); 
element2.AppendChild(element3); 

產生以下XML文件:

<testFile version="1" xmlns="http://www.myschema/schema.xsd"> 
    <testResults> 
    <result resultID="abcdefgh" comment="blah blah blah blah" /> 
    </testResults> 
</testFile> 
1

你不能 「添加命名空間到一個XDocument」。文件不要命名空間。元素和屬性名稱具有名稱空間。

您必須更改文檔中每個元素的名稱空間,以及可能的某些屬性。

+0

我只想將xmlns屬性添加到根節點,所有其他節點都應該默認爲該名稱空間,即沒有前綴。對不起,你是對的我使用的術語文檔和所有元素/屬性鬆散,文檔沒有默認的命名空間。 – wonea

+0

你正在考慮錯誤的方式。 XDocument類和朋友不是XML文檔文本的表示形式。它們是代表文檔語義的一組對象。設置根節點的名稱空間不會改變子節點的名稱空間。 –

3
XNamespace ns = "http://www.myschema/schema.xsd"; 
XDocument xDocument = new XDocument(
new XElement(ns + "testFile", 
    new XAttribute("version", "1"), 
    new XElement(ns + "testResults", 
     new XElement(ns + "result", 
      new XAttribute("resultID", "abcdefgh"), 
      new XAttribute("comment", "blah blah blah blah") 
    )))); 
+0

謝謝,但我想在XDocument生成後添加XNamespace。 – wonea

相關問題