2011-11-17 109 views
0

我有這個XML,我想解析它以便在我的WP應用程序中使用。解析Windows Phone上的在線XML

這是我做過什麼:

private void button1_Click(object sender, System.Windows.RoutedEventArgs e) 
    { 
     WebClient client = new WebClient(); 
     client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted); 
     Uri url = new Uri("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20query%3D%22sushi%22%0A%20%20%20and%20location%3D%22san%20francisco%2C%20ca%22%0A%20%20%20and%20Rating.AverageRating%3E4.0%0A&diagnostics=true", UriKind.Absolute); 
     client.OpenReadAsync(url); 
    } 


    public void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) 
    { 
     try 
     { 
      var xml = XDocument.Load(e.Result); 
      var query = from c in xml.Descendants("Query") 
         select new 
         { 
          ... 
         }; 
     } 
     catch (Exception c) 
     { 
      MessageBox.Show(c.Message); 
     } 
    } 

的問題是在這條線:

var query = from c in xml.Descendants("Query") 

雖然我絕不錯過任何引用...

這是一個很好的解析XML的方法?

我應該使用LINQ to XML還是XmlReader

+2

你說有問題,但你還沒有說*問題是什麼。怎麼了? –

回答

2

你是在正確的軌道上。這是給我的壽司店一個不錯的名單很遠很遠從我的地方:

public void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) 
{ 
    try 
    { 
     var xml = XDocument.Load(e.Result); 
     // get all the result rows from the query (they come as <Result> elements as child elements of <Results> which in turn is a child of <query>) 
     var results = from row in xml.Element("query").Element("results").Elements().Where(element => { return (element.Name.LocalName == "Result"); }) 
         select row; 

     // now I loop all rows and print the title; of course you can 
     // do other stuff here or combine some data processing with the LINQ above 
     // - this is up to you 
     foreach (var result in results) 
     { 
      XElement title = result.Elements().Where(element => { return element.Name.LocalName == "Title"; }).FirstOrDefault(); 
      if (title != null) 
       Debug.WriteLine(title.Value); 
     } 
    } 
    catch (Exception c) 
    { 
     MessageBox.Show(c.Message); 
    } 
} 

(。如果有人知道這些命名空間請賜教處理我使用LocalName繞過他們一個更好的辦法)

+0

我試過使用你的例子,但是當我嘗試把元素()放到一個錯誤時... 在哪裏doest不會出現在我的這裏,即使我只嘗試在xml.Element(「query」)中的行中放置var result = select row; 它返回一個錯誤:無法找到源類型的查詢模式的實現:'System.Xml.Linq.Xelement'。選擇未找到 –

+0

我已經找到了問題! –

+0

我已經找到了問題!缺少對system.linq的引用...所以linq轉換爲xml代碼: XElement xml = XElement.Load(e.Result); var searching = from x in xml.Descendants(「th」) select c; foreach(var中搜索到的項目) { listBox1.Items.Add(item.Value); } –

2

使用LINQ to XML很好......但鏈接到的URL只有一個查詢元素,它是<query>,而不是<Query>。真的不清楚你有什麼問題,但改爲xml.Descendants("query")可能是你所需要的全部...

+0

方法怎麼樣?我應該使用openReadAsync還是DownloadStringAsync?鏈接到XML有抱怨說,它沒有找到我的.xap中的XML ... –

+0

@DiegoVin:爲什麼不使用'XDocument.Load(url)'開始?如果'e.Result'是一個流,那麼我會*期待*它是好的...你可以給*精確的*錯誤信息? –

+1

XDocument.Load不從Windows Phone上的網址加載。個人 - 我使用DownloadStringAsync,因爲它使調試更容易,但OpenReadAsync也可以工作。 –