I'd like to point that XmlTextReader is basically replaced with XmlReader:
Starting with the .NET Framework 2.0, we recommend that you use the
System.Xml.XmlReader class instead.
Though their object model doesn't differ in any significant way.
So, if you want to use XmlTextReader you can do something like:
public static class XmlReaderExtensions
{
public static void EnsureRead(this XmlTextReader reader)
{
var isRead = reader.Read();
if (!isRead)
throw new InvalidOperationException("Failed to read");
}
public static void SkipUntil(this XmlTextReader reader, Func<XmlTextReader, Boolean> isStop)
{
while (!isStop(reader))
{
reader.EnsureRead();
}
}
}
...
var xml = @"<root> <key>businessAddress</key>
<string>Moka</string>
<key>businessName</key>
<string>Moka address</string>
<key>Id</key>
<string>39</string>
<key>Cat</key>
<string>216</string>
<key>deals</key> </root>";
using (var stream = new MemoryStream(Encoding.Default.GetBytes(xml)))
using (var reader = new XmlTextReader(stream))
{
reader.SkipUntil(cur => cur.Value == "Id");
reader.EnsureRead(); // Skip current node
reader.SkipUntil(cur => cur.NodeType == XmlNodeType.Text);
Console.WriteLine("The id from XmlTextReader is {0}", reader.Value);
}
Though to be sure that it will work correctly fail fast with some xml, that doesn't correspond to the given schema, you will have to add a bit more of sanity checks, so...
You can also try LINQ-TO-XML if you are not concerned with entire xml tree being put into the memory:
using (var stream = new MemoryStream(Encoding.Default.GetBytes(xml)))
{
var xdoc = XDocument.Load(stream);
var id = xdoc
.Root
.Elements("key")
.First(element =>
element.Value == "Id")
.ElementsAfterSelf("string")
.First()
.Value;
Console.WriteLine("The id from XDocument is {0}", id);
}