This is the xml that i am trying to read.
<Root>
<some />
<users>
<user>
//stuff
</user>
<user>
//stuff
</user>
<user>
//stuff
</user>
<user>
//stuff
</user>
<users>
</Root>
The following method reads only alternate user elements if xml is one
line.(no new lines in the xml)
but it works fine other wise.
public static IEnumerable<XElement> GetXmlElementsFromPath(this
XmlReader reader, params string[] matchTerms)
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
{
if (matchTerms.Contains
(reader.Name))
{
XElement el = (XElement)
XElement.ReadFrom(reader);
if (el != null)
yield return el;
}
}
break;
}
}
}
Thanks in advance.
> Hi All,
>
>
>
> This is the xml that i am trying to read.
>
> <Root>
> <some />
> <users>
> [...]
> <users>
> </Root>
I assume that's not really your XML.
> The following method reads only alternate user elements if xml is one
> line.(no new lines in the xml)
> but it works fine other wise.
Off the top of my head, I'm guessing that the XNode.ReadFrom() method is
positioning the reader at the next XML node, which you then skip over
using the XmlReader.Read() method at the top of your loop. Looking at the
implementation using Reflector, that seems to be true. The last thing
XNode does before returning is call XmlReader.Read(), advancing the
position of the reader.
The code you posted is practically identical to the code in MSDN, so you
seem to have inherited the bug from there. If my theory is correct, you
should be able to remove the call to XmlReader.Read(), and just repeatedly
call XNode.ReadFrom() instead. Note, of course, you'll have to check the
actual type of the node, and ignore any that aren't XElement instances.
If you do this and confirm the bug in the MSDN code, please submit
feedback to Microsoft regarding the problem in their documentation.
Pete
Thank Pete ....
That is exactly what the problem was..
And that is not the xml that i am using.
Changed to following.. and it looks good for now. I will spend more
time on it on monday to make sure everythingis good..
while (!reader.EOF)
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
{
if (matchTerms.Contains(reader.Name))
//if (reader.Name == tagname)
{
XElement el = (XElement)
XElement.ReadFrom(reader);
if (el != null)
yield return el;
}
else
reader.Read();
}
break;
default:
{
reader.Read();
}
break;
}
}
And i got the code from
http://blogs.msdn.com/xmlteam/archive/2007/03/24/streaming-with-linq-to-xml-part-2.aspx
I will submit feedback..
> [...]
> Changed to following.. and it looks good for now. I will spend more
> time on it on monday to make sure everythingis good..
I haven't tried it myself, but it seems like this would work (and would be
more elegant):
while (!reader.EOF)
{
XElement el = XNode.ReadFrom(reader) as XElement;
if (el != null && matchTerms.Contains(el.Name.ToString()))
{
yield return el;
}
}
Pete