problems with XmlReader and HasAttributes

  • Thread starter Thread starter Michael Heitland
  • Start date Start date
M

Michael Heitland

Hello everybody,

I saw the following code from MS and really have no idea, why the
attributes have to be parsed twice.
Can I omit the second loop?
If I lose some data, please explain it to me with a short XML data
example.

Thanks,
Michael Heitland

XmlTextReader rdr = new XmlTextReader ("data.xml");
while (rdr.Read ()) {
switch (rdr.NodeType) {
case XmlNodeType.Element:
Console.Write ("<" + rdr.Name);
while (rdr.MoveToNextAttribute())
Console.WriteLine (" {0}='{1}'",
rdr.Name, rdr.Value);
Console.Write (">");

//>>> WHY IS THIS SECOND LOOP NECESSARY?
if (rdr.HasAttributes) {
while (rdr.MoveToNextAttribute())
Console.WriteLine (" {0} ", rdr.Value);
}
//<<< WHY IS THIS SECOND LOOP NECESSARY?

break;
case XmlNodeType.Text:
Console.WriteLine (rdr.Value);
break;
case XmlNodeType.EndElement:
Console.WriteLine ("</{0}>", rdr.Name);
break;
}
}
 
Michael,

To add to the confusion, given an XML snippet containing the following say:

<FIELD customer="Fred" id="12345" age="54" employed="permanent" />

now go trace through the XmlNotType.Element section of your switch to reveal
the following output:

<customer customer='Fred'
id='12345'
age='54'
employed='permanent'
So the contents of the second loop will never get processed, and the output
looks like it was formatted incorrectly.

Where was this code?

Thanks.

Dan.
 
Back
Top