Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I skip to an EndElement?

Tags:

c#

xml

xmlreader

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 in https://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?

like image 367
Roi Bar Avatar asked Jan 25 '26 08:01

Roi Bar


1 Answers

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();
}
like image 108
Billy ONeal Avatar answered Jan 27 '26 21:01

Billy ONeal