XML数据管理.NET数据管理、XML、NET

2023-09-04 00:34:51 作者:你给不了我要的未来

我学习的XML数据处理的.NET。我有以下的XML格式。

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

<BOOKS>
    <BOOK>
        <TITLE>book 1</TITLE>
        <AUTHOR>author 1</AUTHOR>       
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </BOOK>
    <BOOK>
        <TITLE>book 2</TITLE>
        <AUTHOR>author 2</AUTHOR>       
        <PRICE>20.90</PRICE>
        <YEAR>1995</YEAR>
    </BOOK>
</BOOKS>

我需要学习如何添加/编辑/删除新的书到XML文件。能否请你指导我什么都班,探讨这些功能。我发现很多类,如的XmlDocument 的XmlTextWriter 等一些网站建议使用LINQ为好。我很困惑,这是去了。有没有什么好的材料可以参考我理解这一点。

I need to learn to add/edit/delete new books to the XML file. Could you please guide me on what all classes to explore for these functionality. I find lot of classes like XmlDocument XmlTextWriter etc. Some sites suggest to use LINQ as well. I am confused as to which was to go. Is there any good material I can refer to understand this.

推荐答案

下面的添加和移除使用LINQ to XML元素的例子:

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

基本上,无论你想用的,只要你舒服的技术。 LINQ到SQL似乎更容易一些,在我看来。

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