我想指出的是XmlTextReader is basically replaced with XmlReader:
從.NET Framework 2.0開始,我們建議您改用 System.Xml.XmlReader類。
雖然他們的對象模型在任何重要方面沒有差異。
所以,如果你想使用XmlTextReader的,你可以這樣做:
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);
}
雖然可以肯定,這將正常工作一些快速失敗XML,這不符合給定的架構,你將不得不添加更多的理智檢查,所以...
您也可以嘗試LINQ-TO-XML,如果你不與整個XML樹被放進記憶有關:
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);
}