XmlTextReader reader = new XmlTextReader("example.xml"); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "book") { string bookTitle = reader.GetAttribute("title"); Console.WriteLine("Title: " + bookTitle); reader.ReadToNextSibling("author"); string authorName = reader.ReadElementContentAsString(); Console.WriteLine("Author: " + authorName); } }
XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; XmlReader reader = XmlReader.Create("example.xml", settings); while (reader.ReadToFollowing("price")) { decimal price = reader.ReadElementContentAsDecimal(); Console.WriteLine("Price: {0:C}", price); reader.ReadToNextSibling("item"); }In this example, we are reading an XML document containing a list of prices and associated items. We use the ReadToFollowing method to locate the next "price" element, and then read its value using the ReadElementContentAsDecimal method. We then use the ReadToNextSibling method to advance to the next "item" element. The package library for the System.Xml namespace is the .NET Framework Class Library.