添加元素在C#中的XML文件 [英] Adding elements to an xml file in C#

查看:111
本文介绍了添加元素在C#中的XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此格式的XML文件:

I have an XML file formatted like this:

<Snippets>
  <Snippet name="abc">
    <SnippetCode>
      testcode1
    </SnippetCode>
  </Snippet>

  <Snippet name="xyz">
    <SnippetCode>      
     testcode2
    </SnippetCode>
  </Snippet>

  ...

</Snippets>

我可以成功加载使用的XDocument的元素,但我有麻烦添加新元素(有很多功能,其中大部分我想并没有为我好工作)。这将如何做?新元素将包含片段的名称标记和代码片段code标记。我的previous方法是打开该文件,并手动使用字符串这虽然作品,是一个非常糟糕的主意创建的元素。

I can successfully load the elements using XDocument, but I have trouble adding new elements (there are many functions and most of which I tried didn't work well for me). How would this be done? The new element would contain the snippet name tag and the snippet code tag. My previous approach was to open the file, and manually create the element using a string which although works, is a very bad idea.

我曾尝试:

        XDocument doc = XDocument.Load(spath);
        XElement root = new XElement("Snippet");
        root.Add(new XElement("name", "name goes here"));
        root.Add(new XElement("SnippetCode", "SnippetCode"));
        doc.Element("Snippets").Add(root);
        doc.Save(spath);

和的结果是这样的:

<Snippet>
    <name>name goes here</name>
    <SnippetCode>
    code goes here
    </SnippetCode>
  </Snippet>

它的工作原理只是名称标记错误地生成的罚款。它应该是

It works fine except that the name tag is generated incorrectly. It should be

<Snippet name="abc"> 

但我不能生成正常。

but I can't generate that properly.

推荐答案

您正在接近,但你想的名字是一个XAttribute而不是的XElement:

You're close, but you want name to be an XAttribute rather than XElement:

 XDocument doc = XDocument.Load(spath); 
 XElement root = new XElement("Snippet"); 
 root.Add(new XAttribute("name", "name goes here")); 
 root.Add(new XElement("SnippetCode", "SnippetCode")); 
 doc.Element("Snippets").Add(root); 
 doc.Save(spath); 

这篇关于添加元素在C#中的XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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