简体   繁体   中英

How can I skip to an EndElement?

I have the next xml:

<work><pageSetup paperSize="9"><a foo="aa"/></pageSetup></work>

I run over the elements with:

using (XmlReader reader = XmlReader.Create(myFile.xml))
{
    while (reader.Read())
    {
        Console.WriteLine(reader.Name + " " + reader.NodeType);
        if (reader.Name == "pageSetup") reader.Skip();
    }
 }

I want to skip to the < /pageSetup> EndElement (when the "cursor" is on < pageSetup> ), but the Skip() method skips over the whole element and its EndElemet . (And this is the correct behavior of Skip() method as written inhttps://msdn.microsoft.com/en-us/library/aa720634(v=vs.71).aspx : The Skip method moves over the current element. If the node type is XmlNodeType.Element, calling Skip moves over all of the content of the element and the element end tag.)

What is the suitable method to use in this case?

You just keep calling Read() until Depth goes back down to the node you start with. Something like this should work (error handling omitted):

int startDepth = reader.Depth; // assume you're on the start element
if (!reader.IsEmptyElement) { // if it is an <empty /> element, there is no end
    reader.Read();
    while (reader.Depth > startDepth) reader.Read();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM