XML Data management in .NET

前端 未结 2 1282
粉色の甜心
粉色の甜心 2021-01-06 23:20

I learning Xml data handling in .NET. I have the following XML format.


    
        book 1
        <         


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-06 23:34

    Here's an example of adding and removing elements using LINQ to XML:

    // load the XML file into an XElement
    XElement xml = XElement.Load(filePath);
    
    // add a new book
    xml.Add(
        new XElement("BOOK",
            new XElement("TITLE", "book 3"),
            new XElement("AUTHOR", "author 3"),
            new XElement("PRICE", 0.1),
            new XElement("YEAR", 2012)));
    
    // remove a book that matches the desired title     
    xml.Elements("BOOK").Where(x => x.Element("TITLE").Value == "book 1").Remove();
    
    // to edit an existing element:
    xml.Elements("BOOK")
        .Single(x => x.Element("TITLE").Value == "book 2") // take a single book
        .Element("AUTHOR").Value = "new author";  // and change its author field
    

    Basically, use whatever you want, as long as you're comfortable with the technology. LINQ to SQL seems a bit easier, in my opinion.

提交回复
热议问题