[英]add data to existing xml file using linq
I am a .net beginner. 我是.net初学者。 I need to add some data to xml file
我需要向xml文件中添加一些数据
the xml file is: xml文件是:
<stock> --- 1st level /* i dont want to create this because this exists */
<items> -- 2nd level
<productname>Toothpaste</productname>
<brandname>Colgate</brandname>
<quantity>12</quantity>
<price>10</price>
</items>
<items>
<productname>Toothpaste</productname>
<brandname>Pepsodent</brandname>
<quantity>20</quantity>
<price>12</price>
</items>
</stock>
I need to add 我需要添加
productname --> Toothpaste
brandname --> CloseUp
quantity --> 16
price --> 15
to their respective tags. 到各自的标签。 The problem I am facing now is that I need to go two levels deep to write to their respective tags, which i dont know how to do.
我现在面临的问题是,我需要深入两个级别才能写入各自的标签,但我不知道该怎么做。
I tried the below code: ( not working ) 我尝试了以下代码:( 不起作用 )
XDocument doc = new XDocument(
new XElement("stock", /* how to go inside existing "stock"? */
new XElement("items",
new XElement("productname", "Toothpaste"),
new XElement("brandname", "CloseUp"),
new XElement("quantity","16"),
new XElement("price","15"))));
There must be some other way to achieve this which I dont know. 我一定不知道有其他方法可以实现这一目标。
Answers not related to linq are also welcome. 也欢迎与linq不相关的答案。 but more preference to linq because I have implemented full linq in my project.
但是更喜欢linq,因为我在项目中实现了完整的linq。
Please Help 请帮忙
Thanks in Advance. 提前致谢。
Assuming you have the original document: 假设您拥有原始文档:
var doc = XDocument.Load(...);
then create a new element (not a document) 然后创建一个新元素(不是文档)
//XDocument doc = new XDocument(
// new XElement("stock", /* how to go inside existing "stock"? */
var newElement = new XElement("items",
new XElement("productname", "Toothpaste"),
new XElement("brandname", "CloseUp"),
new XElement("quantity","16"),
new XElement("price","15"));
And then insert it: 然后将其插入:
doc.Element("stock").Add(newElement);
doc.Save(....);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.