Skip to main content
Home Forums Silverlight Programming Programming with .NET - General Reading number of elements of a XML using XMLReader
4 replies. Latest Post by IanA on September 5, 2008.
(0)
aoifuyu
Member
3 points
9 Posts
09-05-2008 10:45 AM |
Hi all, I think this is a pretty easy one.
Let's say I have this XML named "datafile.xml":
<bookstore> <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0"> ![CDATA[The Autobiography of Benjamin Franklin]]> </book> <book genre="Literary" publicationdate="1995-12-01" ISBN="1-845269-25-5"> ![CDATA["Gone with the Wind"]]> </book> <book genre="Business and Economics" publicationdate="2006-05-25" ISBN="1-452367-96-6"> ![CDATA["Business Law Text and Cases"]]> </book></bookstore>
I'm using XMLReader to parse it.
StringBuilder output = new StringBuilder();XmlReaderSettings settings = new XmlReaderSettings();settings.XmlResolver = new XmlXapResolver();XmlReader reader = XmlReader.Create("datafile.xml");reader.ReadToFollowing("book");string title = reader.ReadElementContentAsString();string book = reader.value;output.Append(title);reader.Close();OutputTextBlock.Text = output.ToString();
Thanks a lot!
Skyrunner
Contributor
2489 points
485 Posts
09-05-2008 10:57 AM |
Using LINQ To XML
XDocument doc = XDocument.Load("datafile.xml");var res = (from n in doc.Descendants("book") select n).Count();
09-05-2008 11:34 AM |
Hi,
Thanks a lot, it worked, but I definitely would like to keep using XMLReader, isn't there any other way it can be solved using it?
09-05-2008 12:08 PM |
int i = 0; for (i = 0; reader.ReadToFollowing("book"); i++) ;
IanA
249 points
50 Posts
09-05-2008 12:21 PM |
I concur with Skyrunner, it is better to use LINQ; it is much more powerful and elegant. If you have a learning curve to climb regarding parsing or generating XML I think its best to spend your time researching LINQ. But just for the record here is how to count your books using a reader:
int count = 0; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("book")) { count++; } }
The SDK documentation for the XmlReader class has a simple example that basically shows you all you need to know about it.