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

查看:37
本文介绍了将元素添加到 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天全站免登陆