I'm trying to read an xml document but the XmlReader.ReadToNextSibling does not work as advertised on this MSDN Documentation
Here is a console example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
namespace ConsoleTestApp
{
class Program
{
static void Main(string[] args)
{
string xmlText = "<xmlRoot><group><item>Item 1</item><item>Item 2</item></group><group><item>Item 3</item><item>Item 4</item></group></xmlRoot>";
using (XmlReader reader = XmlReader.Create(new StringReader(xmlText)))
{
reader.ReadToFollowing("item");
do
{
Console.WriteLine("Item: {0}", reader.ReadInnerXml());
} while (reader.ReadToNextSibling("item"));
}
Console.WriteLine("Press any key to continue...");
Console.Read();
}
}
}
This only outputs one item:
Item: Item 1
Anyone know how i can get this to work?
Please do not suggest using DOM model (XmlDocument). I cannot because these xml files are from different sources and can have many different namespaces and is a huge hassle. I need to get this working.
This is because ReadInnerXml
also advances the reader. So when you get to your first ReadToNextSibling
, you are positioned on Item 2, and there is no next sibling.
This code will read both your items:
string xmlText = "<xmlRoot><group><item>Item 1</item><item>Item 2</item></group><group><item>Item 3</item><item>Item 4</item></group></xmlRoot>";
using (XmlReader reader = XmlReader.Create(new StringReader(xmlText)))
{
reader.ReadToFollowing("item");
do
{
Console.WriteLine("Item: {0}", reader.ReadInnerXml());
} while (reader.Name == "item");
}