将数据添加到使用LINQ现有XML文件 [英] add data to existing xml file using linq

查看:153
本文介绍了将数据添加到使用LINQ现有XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个.NET初学者。我需要一些数据添加到XML文件

I am a .net beginner. I need to add some data to xml file

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"))));



必须有一些其他的方式来实现这个,我不知道。不相关的LINQ
结果答案也欢迎。但更偏爱LINQ,因为我已经实现全LINQ在我的项目。

There must be some other way to achieve this which I dont know.
Answers not related to linq are also welcome. but more preference to linq because I have implemented full linq in my project.

请帮助
结果在此先感谢。

Please Help
Thanks in Advance.

推荐答案

假设你有原始文件:

 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"));

,然后将其:

  doc.Element("stock").Add(newElement);

  doc.Save(....);

这篇关于将数据添加到使用LINQ现有XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆