Difference between XmlNodeType.Element and XmlNodeType.Document?
- It's certainly not a "generic solution", since your code is now completely dependent on information in the XML - your method can only count elements properly if the XML document it's processing contains the flag attribute that you've added.
- The flag attribute's unnecessary. Any time an
XmlReader
starts at the beginning of the stream it's reading, the first element it reads is always going to be the top-level element. It can't possibly be anything else. Instead of adding an attribute to your document to identify the top-level element, you can just use a flag to track whether or not you've read the top-level element yet. Or heck, you can just subtract 1 from the total. - And even if you did need the flag attribute, you're doing it wrong. You're using
MoveToFirstAttribute
to find it. What if there's more than one atttribute on the element? What if the first attribute your code finds whose value isTrue
isn'tRoot
? And what if one of the child elements has an attribute on it with that value? If you're going to use an attribute for this purpose, you should, at the very least, search for it by name. - This code won't count all child elements of the top-level element, it will count all descendant elements. The reader moves from node to node in document order. If an element node has a child node, that child node is the next node that gets read by
Read()
. There are methods of theXmlReader
that you can use to read an entire element and all of its content in one single gulp, but you're not using them. - The condition
reader.NodeType != XmlNodeType.XmlDeclaration && reader.NodeType == XmlNodeType.Element
is redundant: there's no way that a node can be an XML declaration if it's an element.
No comments:
Post a Comment