问题描述
我是 .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>
我需要添加
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 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!