I am a .net beginner. I need to add some data to xml file
我是.net初学者。我需要向xml文件添加一些数据
the xml file is:
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>
I need to add
我需要补充一下
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"))));
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.
必须有其他方法来实现这一点,我不知道。与linq无关的答案也是受欢迎的。但更喜欢linq,因为我在我的项目中实现了完整的linq。
Please Help
Thanks in Advance.
请提前帮助谢谢。
1 个解决方案
#1
21
Assuming you have the original document:
假设你有原始文件:
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"));
And then insert it:
然后插入它:
doc.Element("stock").Add(newElement);
doc.Save(....);
#1
21
Assuming you have the original document:
假设你有原始文件:
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"));
And then insert it:
然后插入它:
doc.Element("stock").Add(newElement);
doc.Save(....);