2008-12-09 68 views
0

確定另一個WPF問題,以及我想這只是一般的.NET。我有一個從URL中獲取的xml文檔。WPF - 使用XMLTextReader搜索XML文檔的值

我想從文檔中獲取多個值(天氣數據,位置和其他一些字符串)。

當我使用XmlTextReader時,我可以調用我的方法來將值拉出。我第一次通過該方法來搜索xml節點並獲取值(XMLTextReader對象)時,我得到了正確的數據,但是XMLTextReader已經死了。不知道爲什麼它被拒之門外。所以我不得不在下面的FindTags ...方法中執行這個UGLY代碼。我想繼續傳遞xtr(XMLTextreader)回到我的find方法。這是讀者的本質嗎?我不希望每次都需要訪問URL ......這似乎也是錯誤的。

幫助..這只是所有感覺不對。

謝謝。

 GetWeatherFeed("97229", "//weather//loc//dnam", "//weather//cc//tmp", "/weather/cc/icon"); 

獲取WeatherFeed方法(剪斷)

 System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(Url that retuns xm); 
     System.Collections.Hashtable ht = new System.Collections.Hashtable(); 

     ht = FindTagsUsingXPthNaviatorAndXPathDocumentNew(xtr, location, temperature, iconid); 
     lblLocation.Content = ht["Location"].ToString(); 
     lblWeatherCondition.Content = ht["Weather"].ToString(); 


public System.Collections.Hashtable FindTagsUsingXPthNaviatorAndXPathDocumentNew(System.Xml.XmlTextReader xtr, string nodeToLocate1, string nodeToLocate2, string nodeToLocate3) 
{ 
    System.Xml.XPath.XPathDocument xpDoc = new System.Xml.XPath.XPathDocument(xtr); 
    System.Xml.XPath.XPathNavigator xpNav = xpDoc.CreateNavigator(); 
    System.Xml.XPath.XPathExpression xpExpression = xpNav.Compile(nodeToLocate1); 

    System.Xml.XPath.XPathNodeIterator xpIter = xpNav.Select(xpExpression); 
    System.Collections.Hashtable ht = new System.Collections.Hashtable(); 

    while (xpIter.MoveNext()) 
    { 
     ht.Add("Location", xpIter.Current.Value); 
    } 

    xpExpression = xpNav.Compile(nodeToLocate2); 

    xpIter = xpNav.Select(xpExpression); 
    while (xpIter.MoveNext()) 
    { 
     ht.Add("Weather", xpIter.Current.Value); 
    } 

    xpExpression = xpNav.Compile(nodeToLocate3); 

    xpIter = xpNav.Select(xpExpression); 
    while (xpIter.MoveNext()) 
    { 
     ht.Add("Icon", xpIter.Current.Value); 
    } 

    return ht; 
} 

回答

0

XmlTextReader無法重置爲開始。 首先下載你的內容,然後使用多個XmlTextReaders(如果必須的話)。

如果您正在下載的文件小,我只想用一個XmlDocument(或的XDocument如果您使用的是.NET 3.5)

0

是不是一個XmlTextReader的SAX讀取器?你不必倒帶流再次讀取文件?

1

這裏就是我所做的...偉大的答案。

  System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(my xml url); 
      System.Xml.XPath.XPathDocument xdoc = new System.Xml.XPath.XPathDocument(xtr); 

      lblLocation.Content = getXmlNodeValue(xdoc, location); 
      lblWeatherCondition.Content = getXmlNodeValue(xdoc, temperature);