"Emsi" <mc@@ness.at> wrote in message news:%2****************@TK2MSFTNGP15.phx.gbl...
how can I read values of child nodes with the XmlTextReader?
: : The problem I see: If I request the field1 at the switch statement, I don't
longer know in which main node I am. Does anyone has a solution for this?
The usual approach to this operates on the concept of detecting when you
enter element 'item' (LocalName = item and NodeType = Element), and
leave element 'item' (LocalName = item and NodeType = EndElement).
In implementing this typical solution, you have a range of choices in using
a flag, counter, or perhaps a Stack.
bool insideItem = false, insideField1 = false;
nmItem = R.NameTable.Add( "item");
nmField1 = R.NameTable.Add( "field1");
while( R.Read( ))
{
if ( R.LocalName == nmItem )
insideItem = ( R.NodeType != XmlNodeType.EndElement );
else if ( insideItem && R.LocalName == nmField1 )
insideField1 = ( R.NodeType != XmlNodeType.EndElement );
else if ( R.NodeType == XmlNodeType.Text && insideField1 )
DoSomething( nmField1, R.Value );
}
Slightly more elegant is to subclass an XmlTextReader, and then
override the ReadStartElement( ) and ReadEndElement( ) methods
to raise/lower the flag and capture the text node in an overload of
ReadString( ). Note that ReadString( ) is also called when reading
attribute values, so in general you may want to have a flag that'd
exclude attributes.
A subclass removes much of the complexity that can arise in writing
code that consumes the XmlTextReader (that complexity moves into
the subclass -- but it's more manageable there and it's services are
reusable from multiple points in your application without repeating
the same state transition logic.
Maybe how to get the childnodes as XmlNode objects or something like this?
I don't want to use XmlDocument if possible because of performance reasons.
You can use an empty XmlDocument here for the purpose of calling
ReadNode( ) on it, which will create an XmlNode from the 'item'
element's content.
Every XmlNode must have an XmlDocument that owns it, so this is
quite impossible without an XmlDocument. The inferior performance,
compared to XmlReaders, that appears to be behind your reasoning
here is primarily the overhead of creating XmlNodes.
An XmlReader can only tell you what it has read. Since you've only just
read the start element of 'item', there are no shortcuts to find out all child
nodes beneath it until you've read through to the end of element 'item'.
Derek Harmon