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