I have this XML file:
我有这个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>
I want to add section :
我想补充一节:
<d>
<info1>test</info1>
<info2>test 2</info2>
</d>
after section <c>
,between ''.
后段
I wrote this code in c# to add define and add section d:
我用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);
But with this code I add <d>
section in <a>
tag and I want to add after <c>
section (<a><b><c>...</c><d>...<d/><f>...</f></b></a>
)
但是这个代码我添加< d >在 <一> 标记部分,我想添加后< c >部分( <一> < b > < c >…< / c > < d > < d / > < f >…< / f > < / b > < / >)
3 个解决方案
#1
3
string path = file.Directory + "//" + file.Name;
XDocument doc = XDocument.Load(path);
doc.Root.Element("b").Add(newElement);
doc.Save(path); // save document
UPDATE (adding between c
and f
):
更新(c和f之间增加):
doc.Root.Element("b").Element("c").AddAfterSelf(newElement);
#2
3
Looks like you're adding it to the wrong tag. Based on your question you want it added to b
:
看起来你把它加错标签了。根据你的问题,你想把它加到b中:
doc.Root.Element("b").Add(newElement);
#3
0
Instead of doc.Element("a").Add(newElement);
而不是doc.Element阀门(“a”)(newElement);
try this:
试试这个:
doc.Root.Element("b").Add(newElement);
#1
3
string path = file.Directory + "//" + file.Name;
XDocument doc = XDocument.Load(path);
doc.Root.Element("b").Add(newElement);
doc.Save(path); // save document
UPDATE (adding between c
and f
):
更新(c和f之间增加):
doc.Root.Element("b").Element("c").AddAfterSelf(newElement);
#2
3
Looks like you're adding it to the wrong tag. Based on your question you want it added to b
:
看起来你把它加错标签了。根据你的问题,你想把它加到b中:
doc.Root.Element("b").Add(newElement);
#3
0
Instead of doc.Element("a").Add(newElement);
而不是doc.Element阀门(“a”)(newElement);
try this:
试试这个:
doc.Root.Element("b").Add(newElement);