3

我有一个从外部 rss 提要获取每日提要的应用程序(此数据在 xml 中)。我有一个允许用户搜索我的数据库的搜索表单,但是,我想使用用户在我的网站上输入的相同搜索字符串来搜索这个 rss 提要,然后只提取相关的内容,并将其显示在我的网站上。

我一直在研究使用 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
            }
        }
4

1 回答 1

4

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);
于 2013-09-26T14:43:53.963 回答