繁体   English   中英

从Xml文件读取帮助

[英]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怎么样? 这使您可以轻松查询对数据的查询-查找,排序,插入,删除...。

我可以解决您的问题,实际上有两个部分。

  1. 从已知ID获取书籍对象
  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; }
 }

要将具有已知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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM