读写xml的选择顺序比较:XmlDocument、XDocument会将xml全部加载到内存,造成内存浪费,不适合大数据xml处理。
XmlReader(以及子类XmlTextReader) 则适合快速的读取,它是只读的,并且只向前读取。其读取的性能比Xml-Linq快;
Xml-Linq 则是.net3.5推出的比较方便快速处理XML数据的一种方式;
1.用XmlRead来快速的读取xml文件并获取其中特定节点的值。
List<string> book=new List<string>(); using (XmlReader read = XmlReader.Create(filePath)) { read.MoveToContent(); while (read.Read()) { if (read.NodeType == XmlNodeType.Element) if (read.Name == "bookstore") { list.Add( Boolean.Parse(read.ReadInnerXml())); } read.Close(); }
2. xml-Path
XmlDocument xml =new XmlDocument (); xml.Load(path); XmlNodeList nodelist = xml.SelectNodes("//book"); foreach (XmlNode item in nodelist) { Response.Write(item.InnerText); }
3.xml-Linq 读写xml
if (File.Exists(path)) { XDocument xd = XDocument.Load(path); var list = from node in xd.Elements("bookstore") select new { books = node.Elements("books"), bookshop=node.Element("bookshop") }; foreach (var item in list) { Response.Write(item.bookshop.Value + "</br>"); foreach (XElement book in item.books) { Response.Write(book.Value+"</br>"); } } }