Search code examples
c#xmlreader

xmlreader skip sibling


I use Xmlreader to parse a xml file.

My method look like

string path = @"E:\tmp\testxml.xml";
using (var reader = XmlReader.Create(path))
{

    bool isOnNode = reader.ReadToDescendant("resource");
    while (isOnNode)
    {
        var element = (XElement)XNode.ReadFrom(reader);

        isOnNode = reader.ReadToNextSibling("resource");
    }
}

But xmlreader skip the sibling node "resource". Moreover when I open the xml file with visual studio, indent and save it, nodes aren't skip.


Solution

  • The XNode.ReadFrom method places the reader after the closing element of the subtree it read. If there is no whitespace in the file, this will be the next <resource> element. This element is then skipped by the ReadToNextSibling call.

    The following should fix it:

    string path = @"E:\tmp\testxml.xml";
    using( var reader = XmlReader.Create(path) )
    {
    
        bool isOnNode = reader.ReadToDescendant("resource");
        while( isOnNode )
        {
            var element = (XElement)XNode.ReadFrom(reader);
    
            if( !reader.IsStartElement("resource") )
                isOnNode = reader.ReadToNextSibling("resource");
        }
    }
    

    If there are no non-<resource> elements as siblings of the <resource> elements, the problem can also be solved simply by using IsStartElement in the while-loop condition.