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

查看:317
本文介绍了在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成功加载元素,但是我添加新元素有麻烦(有很多功能而且我尝试的大部分都对我没有好处)。这将如何做?新元素将包含代码段名称标签和代码段代码标签。我以前的方法是打开文件,并使用一个字符串手动创建元素,尽管它是有用的,但这是一个非常糟糕的主意。

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

但我无法正常生成。

推荐答案

你很接近,但你想要的名字是一个 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天全站免登陆