c# - streaming XElements oddity when there's no whitespace -


this question has answer here:

i've run problem streaming xelements , when there's no whitespace.

given following code msdn documentation streaming xelements,

    public static ienumerable<xelement> streamelements(stream source, string elementname)     {         using (xmlreader reader = xmlreader.create(source))         {             xelement item = null;              reader.movetocontent();              // parse file, save header information when encountered, , yield             // item xelement objects created.              // loop through codefile elements             while (reader.read())             {                 if (reader.nodetype == xmlnodetype.element && reader.name == elementname)                 {                     item = xelement.readfrom(reader) xelement;                      if (item != null)                      {                         yield return item;                     }                 }             }         }     } 

this code fails when elements have no whitespace between them, because xelement.readfrom method moves current position past endelement node. when there's whitespace, reader on text node, , code works fine. when there's no whitespace, reader on next element node, , while(reader.read()) line moves past element node , skipping every other node.

the problem "solved" skipping while(reader.read()) line when correct element returns, ie, add label "readnext:" first line of while loop , add "goto readnext;" right after yield return:

            // loop through codefile elements             while (reader.read())             {                 readnext:                 if (reader.nodetype == xmlnodetype.element && reader.name == elementname)                 {                      item = xelement.readfrom(reader) xelement;                      if (item != null)                      {                         yield return item;                         goto readnext;                     }                 }             } 

note tried xmlreadersettings ignorewhitespace=true on xmlreader.create line.

is there better way here?

yes don't use goto

reader.read(); while (!reader.eof) {     if (reader.nodetype == xmlnodetype.element && reader.name == elementname)     {         item = xelement.readfrom(reader) xelement;          if (item != null)          {             yield return item;         }     }     else     {         reader.read();     } } 

Comments

Popular posts from this blog

java - Could not locate OpenAL library -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

sorting - opencl Bitonic sort with 64 bits keys -