c# - 如何在 XML 文件中的特定部分之后添加一个部分,c#

标签 c# xml winforms

我有这个 XML 文件:

<a>
   <b>
   <name>Ion</name>
   </b>
   <c>
     <article>A10</article>
     <price>100</price>
   </c>
   //here I want to add a new section
   <f>....</f>
   </b>
</a>

我要添加部分:

 <d>
     <info1>test</info1>
     <info2>test 2</info2>
 </d>

节后<c> ,在''之间。

我用 C# 编写了这段代码来添加定义和添加部分 d:

XDocument doc = XDocument.Load(file.Directory + "//" + file.Name);
XElement newElement = new XElement("d",
                                       new XElement("info1", txtInfo1.Text),
                                       new XElement("info2", txtInfo2.Text)
                    );
doc.Element("a").Add(newElement); 

但是使用这段代码我添加了 <d> <a> 中的部分标签,我想在 <c> 之后添加部分 ( <a><b><c>...</c><d>...<d/><f>...</f></b></a>)

最佳答案

 string path = file.Directory + "//" + file.Name;
 XDocument doc = XDocument.Load(path);
 doc.Root.Element("b").Add(newElement); 
 doc.Save(path); // save document

更新(在 cf 之间添加):

 doc.Root.Element("b").Element("c").AddAfterSelf(newElement);

关于c# - 如何在 XML 文件中的特定部分之后添加一个部分,c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20472069/

相关文章:

c# - 哪些因素促使您在应用程序中使用嵌入式脚本?

c# - 如何获得一个 System.Collections.Generic.List<FieldInfo> ,它包含类型 T 对象的所有 FieldInfo,直到类层次结构中的对象?

c# - 如何抽象出不同的 JSON 库实现

c# - 如何将 XML 注释合并回 .cs 文件?

java - Struts2 验证无法正常工作

c# - 向 .NET Windows 窗体 (C#) 添加大量控件时出现问题

c# - winforms应用程序内存使用情况

c# - 如何在 C# (Winforms) 中的 DataGridView 中添加进度条列

c# - c#中有 "zero-sum"变量这样的东西吗?

xml - SQL "For XML Path"- 嵌套结果