2016-03-06 63 views
1

我有一個這樣的XML文件:閱讀下一個值

<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> 

我想讀下一<string>值,如果鍵是ID

因此,我所做的是:

XmlTextReader reader = new XmlTextReader(file); 

while (reader.Read()) 
{ 
    if (reader.Value.Equals("Id")) 
    { 
     reader.MoveToNextAttribute 
    } 
} 

但我沒有成功。

感謝您的幫助

回答

1

你可以使用一個布爾標誌指示是否應該讀下一個元素的值:

bool shouldReadId = false; 
while (reader.Read()) 
{ 
    if (reader.NodeType == XmlNodeType.Text && shouldReadId) 
    { 
     Console.WriteLine(reader.Value); // will print 39 
     shouldReadId = false; 
    } 

    if (reader.Value.Equals("Id")) 
    { 
     // indicate that we should read the value of the next element 
     // in the next iteration 
     shouldReadId = true; 
    } 
} 
1

我想指出的是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); 
} 
0

你的XML看上去非常類似於Plist。所以,聽起來你需要一個Plist庫。不要重新發明輪子,只需使用any of the libraries available on NuGet即可。他們將通過解析XML文件來解決您的問題。

如果您堅持要手動解析XML,請忘記低級SAX類並只使用DOM。使用XDocument更容易。請參閱@EugenePodskal的解決方案。