实际上有两个部分可以解决您的问题。
- 从已知编号
- 得到一本书对象创建一个新的书对象
检索对象:
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