"Niklas E" <ra************@hotmail.com> wrote in message news:eD**************@TK2MSFTNGP11.phx.gbl...
In my case I want to count all suppliers ( <id>Supplier*</id> )
Here's an XmlTextReader subclass that you can pipe the XML
content through and it will count all text nodes starting with an
arbitrary string.
- - - StartsWithReader.cs
using System;
using System.Collections;
using System.IO;
using System.Xml;
public class StartsWithReader : XmlTextReader, IEnumerable
{
private string startsWith;
private ArrayList txtNodes;
public StartsWithReader( string startsWith, Stream inStream) : base( inStream)
{
this.startsWith = startsWith;
this.txtNodes = new ArrayList( );
}
public override bool Read()
{
bool result = base.Read( );
if ( result && ( NodeType == XmlNodeType.Text ) )
{
if ( Value.StartsWith( startsWith))
{
this.txtNodes.Add( this.Value);
}
}
return result;
}
public int Count
{
get
{
return this.txtNodes.Count;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)( this.txtNodes)).GetEnumerator();
}
}
- - -
Running your example XML file through this XmlTextReader
returns a Count of 3,
FileStream fstr = new FileStream( "countStartsWith.xml", FileMode.Open);
StartsWithReader reader = new StartsWithReader( "Supplier", fstr);
while( reader.Read( ) )
;
Console.WriteLine( reader.Count);
fstr.Close( );
Depending on an application's requirements, this subclass is
readily adaptable to serve as a wildcard-pattern match reader,
or a regexp reader, or a variety of other readers.
Derek Harmon