使用LINQ向现有的XML文件添加数据

10

我是一个 .net 初学者。我需要向 XML 文件中添加一些数据。

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>
我需要添加什么,您可以提供更多的上下文信息吗?
productname --> Toothpaste
brandname   --> CloseUp
quantity    --> 16
price       --> 15

我需要写入它们各自的标签。现在我面临的问题是,我需要深入两个级别才能写入它们各自的标签,但我不知道该如何操作。

我尝试了以下代码:(不起作用)

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。

请帮忙
先行致谢。

1个回答

23
假设您拥有原始文件:
 var doc = XDocument.Load(...);

然后创建一个新的元素(不是文档)

  //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(....);

1
谢谢,这个有效 :) Load 是小写的 l,只是一个小修改。 - Mr_Green

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接