[英]Reading from Xml file Help
我有這樣的Xml文件:
<store>
<book id="A1" name="WEB" price="10"/>
<book id="b1" name="C#" price="15"/>
<book id="c1" name="DOT" price="12"/>
<book id="d1" name="JAVA" price="20"/>
<book id="e1" name="C" price="13"/>
</store>
如果新書需要創建新元素和默認ID,那么我的書ID要獲取書名和價格。 請幫幫我
我正在使用.Net 2.0 C Sharp
簡單使用Linq2XML怎么樣? 這使您可以輕松查詢對數據的查詢-查找,排序,插入,刪除...。
我可以解決您的問題,實際上有兩個部分。
要檢索對象:
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; }
}
要將具有已知ID的書加載到對象中:
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));
要創建新書元素:
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以獲得更好的性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.