【问题标题】:add data to existing xml file using linq使用 linq 将数据添加到现有的 xml 文件
【发布时间】:2012-10-08 14:13:51
【问题描述】:

我是 .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。

请帮忙
提前致谢。

【问题讨论】:

    标签: c# xml linq c#-4.0


    【解决方案1】:

    假设你有原始文件:

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

    【讨论】:

    • 谢谢你这个工作:) Load 是小l 只是一个小编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多