使用C#Xdocument类添加子节点 [英] Adding child nodes using c# Xdocument class

查看:42
本文介绍了使用C#Xdocument类添加子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的xml文件.

I have an xml file as given below.

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

  <file:Properties>

</file:Situattion>

我想使用xDocument添加子元素file:Character.这样我的最终xml如下所示

I would like to add the child element file:Character using xDocument.So that my final xml would be like given below

<?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>

我在X#类中使用过的C#代码如下所示.

Code in c# i tried using Xdocument class is given below.

        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")); "行,出现错误:

此操作将创建结构不正确的文档." .

如何在" file:Characters "下添加节点.

How can I add the node under "file:Characters".

推荐答案

您正试图在根目录中直接添加一个额外的 file:Character 元素 .您不想这样做-您想将其添加到 file:Characters 元素下,大概是这样.

You're trying to add an extra file:Character element directly into the root. You don't want to do that - you want to add it under the file:Characters element, presumably.

还请注意, Descendants()从不返回null-如果没有匹配的元素,它将返回一个空序列.所以你想要:

Also note that Descendants() will never return null - it will return an empty sequence if there are no matching elements. So you want:

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 调用,这样,只有实际上对文档进行了更改.

Note that I've used more conventional naming, Path.Combine, and also moved the Save call so that you'll only end up saving if you've actually made a change to the document.

这篇关于使用C#Xdocument类添加子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆