到达xml行中的数值

时间:2017-03-27 06:50:55

标签: c# xml

我在这里有这行代码:

foreach (SyndicationItem item in feed.Items)
{
    DataRow r = table.NewRow();
    r["Date"] = item.PublishDate.Date.ToString("yyyy-MM-dd");
    r["Publish Time"] = item.PublishDate.TimeOfDay;
    r["Event"] = item.Title.Text;
    table.Rows.Add(r);
}

和这个xml(rss feed)'description'行:

<description>
    <table cellspacing='5' border='0'> 
        <tr> 
            <th>Time Left</th> 
            <th>Impact</th> 
            <th>Previous</th> 
            <th>Consensus</th> 
            <th>Actual</th> 
        </tr> 
        <tr> 
            <td>1h 17min</td> 
            <td><img src="http://www.myfxbook.com/images/transparent.png" class="sprite sprite-common sprite-medium-impact"/></td> 
            <td> 111.0 </td> 
            <td> 111.0 </td> 
            <td> </td> 
        </tr> 
    </table>
</description>

我需要检索与xml行中显示的此表中的'Impact''Previous''Consensus'和'Actual'列匹配的值(数字或字符串)。 然后将其导入数据表行,就像我在c#代码中所做的那样。 有效的方法吗?

2 个答案:

答案 0 :(得分:1)

以下是您的特定XML的示例(看似是带有标题和值的2行HTML表格;匹配两行中的列数):

您可以使用XDocument和LINQ:

提取和配对值
//Parse data - in this example, stored in a string
XDocument xDoc = XDocument.Parse(data);

//Select table rows (tr elements)
var tableRows = from tr in xDoc.Descendants("tr")
                select tr;

//Extract column headings
var headings = from th in tableRows.Descendants("th")
               select th.Value;

//Extract column data
var values = from td in tableRows.Descendants("td")
             select td.Value;

//Create pairs; can be adapted to other types, such as C# 7 tuples, a Dictionary, etc.
var pairs = Enumerable.Zip(headings, values, (name, value) 
    => new Tuple<string, string>(name, value));

然后,您可以直接从“配对”集合中访问数据(包括将其存储在数据库中)。

答案 1 :(得分:0)

@CoolBots,这是一个简单的控制台应用程序:

public void DisTranswe()
    {
        Console.Clear();
        FileStream fs = new FileStream("TransactionHistory\\weekend\\transcationhistory.txt", FileMode.Open, FileAccess.Read);
        StreamReader sr = new StreamReader(fs);
        while ((str = sr.ReadLine()) != null)
        {
            string[] data = str.Split('#');
            string id = data[0];
            string date = data[1];
            string qty = data[2];
            string payment = data[3];
            string note = data[4];

            //output
            Console.WriteLine("IdTransaksi");
            Console.WriteLine(id);
            Console.WriteLine("DateTransaksi");
            Console.WriteLine(date);
            Console.WriteLine("QOH");
            Console.WriteLine(qty);
            Console.WriteLine("TotalPayment");
            Console.WriteLine(payment);
            Console.WriteLine("Note");
            Console.WriteLine(note);

        }
        sr.Close();
        fs.Close();
    }