c# - 使用 linq 将数据添加到现有的 xml 文件

标签 c# xml linq c#-4.0

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

请帮忙
提前致谢。

最佳答案

假设您有原始文档:

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

关于c# - 使用 linq 将数据添加到现有的 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12783525/

相关文章:

c# - 我现在应该为此目的使用抽象基类吗?

sql-server - 在 SQL Server 中存储具有标准结构的 XML 是对 XML 数据类型的错误使用吗?

java - 更改列表项背景边框的颜色

c# - 赋值的左侧必须是变量

SQL RANDOM ORDER BY 连接表

c# - 如何将 OrderBy()、Where() 等作为参数传递给处理集合

c# - WPF中基于RowStyle的CellStyle

c# - 从ViewModel访问数据库是否违反了MVC原则?

c# - DataGrid wpf MVVM 内的按钮

xml - 删除由 appendChild 添加的不需要的(空的)xmlns 属性