XmlReader for immediate descendents

M

Marc Gravell

I have an xml-reader positioned at an element.

I want to read a: all of the attributes of the element, and b: all of the
immediate child-elements of the current element.

The first (attributes) seems very simple:

if (reader.MoveToFirstAttribute()) {
do {
name = reader.Name;
value = reader.Value;
// do something with these...
} while (reader.MoveToNextAttribute());
}

However, unless I am missing something it is much harder to do this for the
immediate descendents, particularly if you don't know the names in advance.
It looks like I could run into all sorts of mess involving Depth and
NodeType and/or running into attributes.

Does anybody have a simple example of doing this? All I really want to do is
read the text value of A, B and C (dynamically; I don't know their names in
advance) in the following, but ideally bomb-proof so that it doesn't break
if A has an attribute and B has a sub-tree or something (etc):

<ContextElement><A>valueA</A><B>valueB</B><C>valueC</C></ContextElement>

returing valueA, valueB and valueC; ideally it would also cope with:

<ContextElement><A
ID="1">valueA</A><B>valueB<SubTree/></B><C>valueC</C></ContextElement>

(and I'd ideally leave the reader at the closing tag ready for the next
iteration)

Any clues here?

Marc
 
M

Marc Gravell

For ref, my current code looks like the following; seems a bit overkill - am
I missing anything?

int targetDepth = reader.Depth + 1;
while(reader.Read()) {
int currentDepth = reader.Depth;
if (reader.NodeType == XmlNodeType.EndElement &&
reader.Depth < targetDepth) {
break; // reached end of element
}
if (currentDepth > targetDepth) { // too deep
reader.Skip();
} else if (currentDepth == targetDepth &&
reader.NodeType == XmlNodeType.Element) {
name = reader.Name;
value = reader.ReadElementContentAsString();
// do something with these
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top