2013-07-29 53 views
8

我有一個xml文件,如下所示。使用c#添加子節點Xdocument類

<?xml version="1.0" encoding="utf-8"?> 
<file:Situattion xmlns:file="test"> 

    <file:Properties> 

</file:Situattion> 

我想補充的子元素文件:使用xDocument.So性格,我的最終的XML會像在C#下面給出

<?xml version="1.0" encoding="utf-8"?> 
    <file:Situattion xmlns:file="test"> 

    <file:Characters> 

    <file:Character file:ID="File0"> 
    <file:Value>value0</file:Value> 
    <file:Description> 
     Description0 
    </file:Description> 
    </file:Character> 

<file:Character file:ID="File1"> 
    <file:Value>value1</file:Value> 
    <file:Description> 
    Description1 
    </file:Description> 
    </file:Character> 

    </file:Characters> 

代碼,我使用的XDocument類嘗試下面給出。

 XNamespace ns = "test"; 
     Document = XDocument.Load(Folderpath + "\\File.test"); 

     if (Document.Descendants(ns + "Characters") != null) 
     { 

      Document.Add(new XElement(ns + "Character")); 
     } 
     Document.Save(Folderpath + "\\File.test"); 

在行 「Document.Add(new XElement(ns + "Character"));」,我得到一個錯誤:

"This operation would create an incorrectly structured document."

如何在「file:Characters」下添加節點。

+0

你用XPATH還是'XQuery'查看了當前頁面右邊的' - > Related'鏈接,有很多實例供你調查 – MethodMan

+1

@DJKRAZE:沒有必要在這裏完全可以使用XPath或XQuery,我不相信他們甚至會讓代碼更簡單。 –

回答

11

你試圖額外file:Character元素直接添加到根。你不想那樣做 - 你想把它添加到file:Characters元素下,大概是這樣。

另請注意,Descendants()從不返回null - 如果沒有匹配的元素,它將返回一個空序列。所以,你想:

var ns = "test"; 
var file = Path.Combine(folderPath, "File.test"); 
var doc = XDocument.Load(file); 
// Or var characters = document.Root.Element(ns + "Characters") 
var characters = document.Descendants(ns + "Characters").FirstOrDefault(); 
if (characters != null) 
{ 
    characters.Add(new XElement(ns + "Character"); 
    doc.Save(file); 
} 

請注意,我用更傳統的命名,Path.Combine,也感動了Save通話,讓你只挽救了,如果你實際上已經做了更改的文件。

+0

什麼是「文檔」對象的類型? – TVSuser1654136

+0

得到一個錯誤「':'字符,十六進制值0x3A,不能包含在名稱中。」 – TVSuser1654136

+1

@ user1654136:'doc'是'XDocument'。如果你得到這個錯誤,這表明你使用'「file:Character」'作爲本地名稱而不是'ns +「字符」'或者類似的東西。你不應該在我提供的代碼中遇到這個問題。 –

4
Document.Root.Element("Characters").Add(new XElement("Character", new XAttribute("ID", "File0"), new XElement("Value", "value0"), new XElement("Description")), 
     new XElement("Character", new XAttribute("ID", "File1"), new XElement("Value", "value1"), new XElement("Description"))); 

注:我還沒有爲簡潔的命名空間。你必須添加這些。