[英]Adding child nodes using c# Xdocument class
我有一個xml文件,如下所示。
<?xml version="1.0" encoding="utf-8"?>
<file:Situattion xmlns:file="test">
<file:Properties>
</file:Situattion>
我想添加子元素文件:使用xDocument.So的字符,我的最終xml將如下所示
<?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類嘗試的c#中的代碼。
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
”下添加節點。
您正在嘗試添加一個額外的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
調用,這樣如果您實際對文檔進行了更改,則最終只會保存。
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")));
注意:為簡潔起見,我沒有包含命名空間。 你必須添加這些。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.