2010-06-29 105 views
0

閱讀中,我對XML文件是這樣的:從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> 

我有書編號想得到的書的名稱和價格,如果其新書只需要創建新的元素和默認密碼。請幫我在這

我使用的.Net 2.0升C

+0

XML文件 <書籍ID = 「A1」 名稱= 「WEB」 價格= 「10」/> <書籍ID = 「B1」 名稱= 「C#」 價格= 「15」/> <書id =「c1」name =「DOT」price =「12」/> Hukam 2010-06-29 11:08:45

回答

1

實際上有兩個部分可以解決您的問題。

  1. 從已知編號
  2. 得到一本書對象創建一個新的書對象

檢索對象:

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來獲得更好的性能。

+0

感謝您的code.It幫助我很多 – Hukam 2010-06-30 09:29:01

1

如何簡單地使用Linq2XML? 這使您可以輕鬆查詢訪問您的數據 - 查找,排序,插入,刪除....

+0

我只有.Net 2.0框架 – Hukam 2010-06-29 11:19:18

+0

會很好的LINQ2XML例子或解決方案的鏈接。 – BerggreenDK 2010-11-06 00:34:26