将Rss读入DataTable

时间:2015-01-23 01:40:11

标签: c# xml c#-4.0 datatable rss

我正在阅读RSS并转换为dataTable。这是我正在使用的代码。

这是我的rss格式

<rss version="2.0">
<channel>
<title>First Choice Liquor</title>
<link>https://www.1stchoice.com.au</link>
<copyright>(c) 2015, First Choice Liquor</copyright>
  <item>
    <title>McWilliams Hanwood Chardonnay 750mL in any six</title>
    <product_name>McWilliams Hanwood Chardonnay 750mL</product_name>

    <description>
    Inexpensive chardonnay need not be ordinary. Complexity and elegance on a budget. A blend of Chardonnays from all over the… Price may vary per state.
    </description>
    <link>
    https://www.1stchoice.com.au/White Wine/mcwilliams-hanwood-chardonnay-750ml_121385?forceState=QLD
    </link>
 </item>
 <item>...<item>
 <item>...<item>
 <item>...<item>
</channel>

我希望我的DataTable只有三列。

title, product_name, description

然后行填充相关值。

string url = "http://localhost/sample_qld.xml";
XElement x = XElement.Load(url);
DataTable dtr = BuildDataTable(x);

private static DataTable BuildDataTable(XElement x)
{
    DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("title"));
        dt.Columns.Add(new DataColumn("product_name"));
        dt.Columns.Add(new DataColumn("description"));
        foreach (var d in x.Descendants())
        {
            DataRow drow = dt.NewRow();
            if (x.Name.ToString() == "title")
            {
                drow[0] = d.Value;
            }
            if (x.Name.ToString() == "product_name")
            {
                drow[1] = d.Value;
            }
            if (x.Name.ToString() == "description")
            {
                drow[2] = d.Value;
            }
        }

    return dt;
}

现在我能够将所有RSS XML转换为xElement X,其中包含所有xml,但我无法按照自己的意愿制作数据表。我做错了什么帮助?我只需要三行

2 个答案:

答案 0 :(得分:1)

在这里,我发布了答案重新!下次不要删除带答案的问题,特别是当他们 upvoted

        string url = "http://www.test.com/feed/";
        XmlReader reader = XmlReader.Create(url);
        SyndicationFeed feed = SyndicationFeed.Load(reader);
        reader.Close();

        DataTable tbl = new DataTable();
        tbl.Columns.Add("Title");

        foreach (SyndicationItem item in feed.Items)
        {
            DataRow row = tbl.NewRow();

            String title= item.Title.Text;
            row["Title"]= title;
            table.Rows.Add(row);   
        }

您需要使用SyndicationFeed来阅读RSS。您需要将System.ServiceModel引用添加到项目中。

答案 1 :(得分:0)

您需要将行添加到表中。只需创建一个新的,就不会自动将其添加到表中:

            foreach (var d in x.Descendants())
        {
            DataRow drow = dt.NewRow();
            if (x.Name.ToString() == "title")
            {

                drow[0] = d.Value;

            }
            if (x.Name.ToString() == "product_name")
            {

                drow[1] = d.Value;

            }
            if (x.Name.ToString() == "description")
            {

                drow[2] = d.Value;

            }
            dt.Rows.Add(drow);
        }