简体   繁体   English

从Xml文件读取帮助

[英]Reading from Xml file Help

I have Xml file like this: 我有这样的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>

I have book Id want to get book name and price if its new book need to create new element and default id only. 如果新书需要创建新元素和默认ID,那么我的书ID要获取书名和价格。 please help me on this 请帮帮我

I am using .Net 2.0 c sharp 我正在使用.Net 2.0 C Sharp

How about simply using Linq2XML? 简单使用Linq2XML怎么样? This gives you easy query access to your data - find, sort, insert, delete.... 这使您可以轻松查询对数据的查询-查找,排序,插入,删除...。

There's actually two parts to your problem that I can. 我可以解决您的问题,实际上有两个部分。

  1. Get a book object from known Id 从已知ID获取书籍对象
  2. Create a new book object 创建一个新书对象

To retrieve the object: 要检索对象:

 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; }
 }

To load the book with known Id into the object: 要将具有已知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));

To create a new book element: 要创建新书元素:

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);

Where _path is the path to your XML document. _path是XML文档的路径。

I hope this helps. 我希望这有帮助。 Also remember that XmlDocument is an in-memory or cached tree representation of an XML document. 还请记住,XmlDocument是XML文档的内存中或缓存的树表示形式。 It is somewhat resource-intensive, if you have a large XML document and not enough memory to consume, use XmlReader and XmlWriter for better performance. 如果您有一个大型XML文档并且没有足够的内存来使用,则它会占用大量资源,请使用XmlReader和XmlWriter以获得更好的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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