2013-09-26 232 views
1

我有一個應用程序從外部rss訂閱源獲取每日訂閱源(此數據以xml格式)。 我有一個搜索表單,允許用戶搜索我的數據庫,但是,我想使用用戶在我的網站上輸入的相同搜索字符串來搜索此RSS源,然後只提取相關內容,並將其顯示在我的網站上。從外部網站獲取xml數據

我一直在尋找使用LINQ使用此代碼讀取XML文件:

XElement xelement = XElement.Load("..\\..\\Employees.xml"); 
IEnumerable<XElement> employees = xelement.Elements(); 
Console.WriteLine("List of all Employee Names along with their ID:"); 
foreach (var employee in employees) 
{ 
    Console.WriteLine("{0} has Employee ID {1}", 
     employee.Element("Name").Value, 
     employee.Element("EmpId").Value); 
} 

的問題,我有這個,在代碼中我用的不是文件名的URL:

XElement xelement = XElement.Load("..\\..\\Employees.xml"); 

應該是:

XElement xelement = XElement.Load("http://www.test.com/file.xml"); 

我想也許我應該在內容存入數組Ø什麼東西,並檢查以確保searchString是否在其中?

我不知道如何繼續,什麼是最好的使用,也許我不應該使用LINQ?

因此使用下面這裏的反應是對我做了什麼:

public void myXMLTest() 
     { 
      WebRequest request = WebRequest.Create("http://www.test.com/file.xml"); 
      WebResponse response = request.GetResponse(); 
      Stream dataStream = response.GetResponseStream(); 

      XElement xelement = XElement.Load(dataStream); 
      IEnumerable<XElement> employees = xelement.Elements(); 


      MessageBox.Show("List of all Employee Names along with their ID:"); 

      foreach (var employee in employees) 
      { 
       MessageBox.Show(employee.Name.ToString()); 
       /* the above message box gives me this: 
       {http://www.w3.org/2005/Atom}id 
       {http://www.w3.org/2005/Atom}name 
       {http://www.w3.org/2005/Atom}title 
       etc 
       */ 
       MessageBox.Show(employee.Element("name").Value);//this gives me error 
      } 
     } 
+0

在我回答這個問題:http://stackoverflow.com/questions/10412494/timeout-error-when -loading-xml-from-url/10412665#10412665我給出了從URL返回XmlDocument的通用方法。這將需要最少的工作來轉換爲返回XDocument。 – dash

+0

如果這是一種標準的RSS格式(RSS或Atom),您還需要處理LINQ語句中的命名空間。 – Tim

+0

請根據你的意見看我的新編輯 – NULL

回答

2

你將不得不做更多的工作不僅僅是提供它的URL。

相反,您將需要使用WebRequest類來獲取XML文件。如果請求成功,您可以將其用作XElement.Load的參數。

例(僅是說明性的,對皮特的愛添加一些錯誤處理):

WebRequest request = WebRequest.Create("http://www.test.com/file.xml"); 
WebResponse response = request.GetResponse(); 
Stream dataStream = response.GetResponseStream(); 
XElement doc = Xelement.Load(dataStream); 
+0

感謝您的建議,請根據您的建議答案查看我的編輯。 – NULL

+0

@Menew您的編輯不會提示您想要問什麼問題。提出另一個問題可能會更好。 – villecoder