Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

c# - add data to existing xml file using linq

I am a .net beginner. I need to add some data to xml file

the xml file is:

<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.

Please Help
Thanks in Advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...