實際上有兩個部分可以解決您的問題。
- 從已知編號
- 得到一本書對象創建一個新的書對象
檢索對象:
public class Book
{
public Book(string id, string name, decimal price)
{
Id = id;
Name = name;
Price = price;
}
public string Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
書與已知的編號裝入對象:
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(_path);
XmlNode xmlNode = xmlDocument.SelectSingleNode(@"//book[@id='" + id + "']");
return xmlNode == null ? new Book(id, string.Empty, 0) : new Book(id, xmlNode.Attributes["name"].Value, decimal.Parse(xmlNode.Attributes["price"].Value));
To cr吃掉一個新的書籍元素:
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(_path);
XmlElement newBook = xmlDocument.CreateElement("book");
newBook.SetAttribute("id", book.Id);
newBook.SetAttribute("name", book.Name);
newBook.SetAttribute("price", book.Price.ToString());
xmlDocument.DocumentElement.AppendChild(newBook);
xmlDocument.Save(_path);
其中_path是XML文檔的路徑。
我希望這會有所幫助。還要記住,XmlDocument是XML文檔的內存或緩存樹表示。如果你有一個大的XML文檔並且沒有足夠的內存消耗,那麼這需要大量資源,使用XmlReader和XmlWriter來獲得更好的性能。
XML文件 <書籍ID = 「A1」 名稱= 「WEB」 價格= 「10」/> <書籍ID = 「B1」 名稱= 「C#」 價格= 「15」/> <書id =「c1」name =「DOT」price =「12」/> –
Hukam
2010-06-29 11:08:45