Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a dictionary or list from string(HTML tag included) in C#

A have a string like this:

string s = @"
    <tr>
    <td>11</td><td>12</td>
    </tr>
    <tr>
    <td>21</td><td>22</td>
    </tr>
    <tr>
    <td>31</td><td>32</td>
    </tr>";

How to create Dictionary<int, int> d = new Dictionary<int, int>(); from string s to get same result as :

d.Add(11, 12);
d.Add(21, 22);
d.Add(31, 32);
like image 914
loviji Avatar asked Dec 07 '22 04:12

loviji


2 Answers

You should use the HTML Agility Pack.

For example: (Tested)

var doc = new HtmlDocument();
doc.LoadHtml(s);
var dict = doc.DocumentNode.Descendants("tr")
              .ToDictionary(
                  tr => int.Parse(tr.Descendants("td").First().InnerText),
                  tr => int.Parse(tr.Descendants("td").Last().InnerText)
              );

If the HTML will always be well-formed, you can use LINQ-to-XML; the code would be almost identical.

like image 70
SLaks Avatar answered Apr 12 '23 22:04

SLaks


Code

using RE=System.Text.RegularExpressions;

....

public void Run()
{
    string s=@"
<tr>
<td>11</td><td>12</td>
</tr>
<tr>
<td>21</td><td>22</td>
</tr>
<tr>
<td>31</td><td>32</td>
</tr>";

    var mcol= RE.Regex.Matches(s,"<td>(\\d+)</td><td>(\\d+)</td>");
    var d = new Dictionary<int, int>();

    foreach(RE.Match match in mcol)
        d.Add(Int32.Parse(match.Groups[1].Value),
              Int32.Parse(match.Groups[2].Value));

    foreach (var key in d.Keys)
        System.Console.WriteLine("  {0}={1}", key, d[key]);
}
like image 20
Cheeso Avatar answered Apr 12 '23 23:04

Cheeso