开发者

xmlreader skip sibling

I use Xmlreader to parse a xml file.

My method look like

string path = @"E:\tmp\testxml.xml开发者_StackOverflow中文版";
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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜