2010-06-29 100 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