Skip to main content

Microsoft Silverlight

Answered Question Reading number of elements of a XML using XMLReaderRSS Feed

(0)

aoifuyu
aoifuyu

Member

Member

3 points

9 Posts

Reading number of elements of a XML using XMLReader

 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();
 
My question is, how can I read the number of elements in the XML, in this case "book"? it should be 3. I've tried validating it using HasValue, but it does not work.
Thanks a lot! 
 

Skyrunner
Skyrunner

Contributor

Contributor

2489 points

485 Posts

Silverlight MVP

Re: Reading number of elements of a XML using XMLReader

Using LINQ To XML

 

XDocument doc = XDocument.Load("datafile.xml");

var res = (from n in doc.Descendants("book")
select n).Count();
  

aoifuyu
aoifuyu

Member

Member

3 points

9 Posts

Re: Reading number of elements of a XML using XMLReader

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?

Skyrunner
Skyrunner

Contributor

Contributor

2489 points

485 Posts

Silverlight MVP
Answered Question

Re: Reading number of elements of a XML using XMLReader

  

int i = 0;
for (i = 0; reader.ReadToFollowing("book"); i++) ;
 

IanA
IanA

Member

Member

249 points

50 Posts

Re: Reading number of elements of a XML using XMLReader

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. 

  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities