如何使用C#中的元素添加具有特定属性名称的新XML元素 [英] How to add new XML element with a particular attribute name inside with an element in C#
本文介绍了如何使用C#中的元素添加具有特定属性名称的新XML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下xml文件,我想将新数据添加到名称为TES的特定元素和
I have below xml file and i want to add new data to a particular element with name TES and
<product ip="3,4,4,4,4" op="33" />
<?xml version="1.0" encoding="utf-8"?>
<root>
<Brand name="TES">
<product ip="40,67, 0,0,0" op="0" />
<product ip="49,25, 4,4,0" op="0" />
<product ip="40,5, 3,64,0" op="0" />
<product ip="85,27, 6,6,0" op="0" />
<product ip="8,27, 6,6,0 " op="0" />
<product ip="23,5, 4,1,0" op="0" />
<product ip="26,25,0,33,10" op="0" />
<product ip="100,0,0,0,0" op="0" />
</Brand>
<Brand name="SW">
<product ip="0, 1, 0,0,0" op="1" />
<product ip="0, 100,0,0,0" op="1" />
<product ip="0, 25,0,75,0" op="1" />
<product ip="0, 25,0,75,0" op="1" />
<product ip="0, 35,0,55,0 " op="1" />
<product ip="42, 43,0,82,6" op="1" />
<product ip="24, 7,1,17,0" op="1" />
</Brand>
</root>
我尝试过:
i在c#下方试过,但它只为第一个现有元素添加属性
What I have tried:
i had tried below c# but it only add attributes to first existing element
XElement root = XElement.Load("sample.xml");
root.Element("Brand").Element("product").Add( new XAttribute("IP", "3,4,4,4,4"),new XAttribute("OP", "33"));
root.Save("output.xml");
推荐答案
在这里猜一下,因为它不是你要问的,但是你想要这样做......
Taking a guess here, because its not quite what you are asking, but are you trying to do this...
XElement element = root
.Elements("Brand")
.Where(e => e.Attribute("name").Value == "TES")
.Single();
element.Add(
new XElement("product",
new XAttribute("ip", "3,4,4,4,4"),
new XAttribute("op", "33")));
如果没有,我会提供两个小的XML文档: BEFORE文档和AFTER文档,显示您想要做的事情(正如我在评论中所建议的那样)。
If not, I'd provide two small XML documents: a BEFORE document and an AFTER document, showing what you want to do (as I suggested in the comments).
这篇关于如何使用C#中的元素添加具有特定属性名称的新XML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文