XML操作

XmlDocument document = new XmlDocument();
document.Load("Data\\books.xml");

List<Book> bookList = new List<Book>();
foreach (XmlElement book in document.DocumentElement.ChildNodes)
{
    string isbn = book.GetAttribute("ISBN").ToString();//属性
    string genre = book.GetAttribute("genre").ToString();//属性
    string title = book.SelectSingleNode("title").InnerText;//节点
    string author = book.SelectSingleNode("author").InnerText;
    string price = book.SelectSingleNode("price").InnerText;
    Book bookInfo = new Book();
    bookInfo.ISBN = isbn;
    bookInfo.Genre = genre;
    bookInfo.Title = title;
    bookInfo.Author = author;
    bookInfo.Price = Convert.ToDouble(price);
    bookList.Add(bookInfo);
}

//根据特定的值获取节点

XmlNode targetNode = document.SelectSingleNode("bookstore/book[@ISBN='2-3631-4']");//获得目标节点
//以下两种写法效果一样
XmlNode targetNode = document.SelectSingleNode("/bookstore/book/title[text()='CS从入门到精通']");//获得目标节点
XmlNode targetNode = document.SelectSingleNode("/bookstore/book/title[.='CS从入门到精通']");//获得目标节点

book.xml

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </book>
</bookstore>


 

posted @ 2013-11-26 17:36  pnljs  阅读(177)  评论(0编辑  收藏  举报