我有这个 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
更新(在 c
和 f
之间添加):
doc.Root.Element("b").Element("c").AddAfterSelf(newElement);
关于c# - 如何在 XML 文件中的特定部分之后添加一个部分,c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20472069/