Reputation: 1589
I have an app that gets a daily feed from an external rss feed (this data is in xml). I have a search form that allows users to search my database, however, i would like to use the same searchstring that users enter on my site to search this rss feed, then extract only whats relevant, and display that on my website.
I have been looking at reading xml file using linq using this code:
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);
}
the problem i have with this is, where in the code do i use a url instead of a file name:
XElement xelement = XElement.Load("..\\..\\Employees.xml");
should be:
XElement xelement = XElement.Load("http://www.test.com/file.xml");
I am thinking maybe i should store the content into an array or something, and check to make sure if the searchString is in it?
I am not sure how to proceed and whats best to use, maybe i shouldn't even use linq??
so using the responses below here is what i have done:
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
}
}
Upvotes: 3
Views: 5344
Reputation: 13493
You're going to have to do a bit more work than just providing it a URL.
Instead, you're going to need to get the XML file using the WebRequest class. Provided the request is successful, you can then turn around use that as your argument to XElement.Load.
Example (illustrative only, for the love of Pete add some error handling):
WebRequest request = WebRequest.Create("http://www.test.com/file.xml");
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
XElement doc = Xelement.Load(dataStream);
Upvotes: 5