Search code examples
c#xmlxml-parsingxmldocumentxmlreader

XmlReader: is there a way of finding the first child, and next sibling?


I am porting code that uses an XmlDocument. XmlNode has a FirstChild and NextSibling property. Using XmlReader, is there a way of parsing until the first child, or the next sibling, given the xmlreader has parsed to an arbitrary element in the xml?


Solution

  • With XmlRreader, you are working in other scheme. You always are at some current node, and you switch to next one. For the current node, you can ask IsEmptyElement (which says if the tag is of the form <something attr=value/>. If the element is empty, clearly you have no child items.

    Consider the case when IsEmptyElement is false, now you have something like <something> <maybechild/> </something>. You can say ReadStartElement, which will move you to the next position. For the next position you check IsStartElement. If it's true, you have a child and you are at it. If not, you are at </something> and there are no children.

    Some more documentation: http://msdn.microsoft.com/en-us/library/t9bfea29.aspx.