我有一个xml文件,如下所示.
<?xml version="1.0" encoding="utf-8"?>
<file:Situattion xmlns:file="test">
<file:Properties>
</file:Situattion>
Run Code Online (Sandbox Code Playgroud)
我想添加子元素文件:使用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>
Run Code Online (Sandbox Code Playgroud)
下面给出了使用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");
Run Code Online (Sandbox Code Playgroud)
在" Document.Add(new XElement(ns + "Character"));" 行,我收到一个错误:
"This operation would create an incorrectly structured document.".
如何在" file:Characters" 下添加节点.
Jon*_*eet 17
您正尝试将额外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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,我使用了更常规的命名,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")));
Run Code Online (Sandbox Code Playgroud)
注意:为简洁起见,我没有包含命名空间.你必须添加这些.