471,627 Members | 1,510 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,627 software developers and data experts.

XmlReader for immediate descendents

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):


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


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

Any clues here?

Feb 3 '06 #1
1 1948
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
} else if (currentDepth == targetDepth &&
reader.NodeType == XmlNodeType.Element) {
name = reader.Name;
value = reader.ReadElementContentAsString();
// do something with these
Feb 3 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by Matthew Heironimus | last post: by
1 post views Thread by Angus Lepper | last post: by
6 posts views Thread by Rob Meade | last post: by
5 posts views Thread by heday60 | last post: by
1 post views Thread by XIAOLAOHU | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.