创建字符串在C#字典或列表(包括HTML标记) [英] create a dictionary or list from string(HTML tag included) in C#

查看:189
本文介绍了创建字符串在C#字典或列表(包括HTML标记)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个有这样的字符串:

 字符串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>中;



如何创建词典< INT,INT> D =新词典< INT,INT>(); 从字符串的取值
获得同样的结果:

  d.Add(11,12); 
d.Add(21,22);
d.Add(31,32);


解决方案

您应该使用的HTML敏捷性包



例如:(测试)

  VAR DOC =新的HTMLDocument(); 
doc.LoadHtml(S);
VAR字典= doc.DocumentNode.Descendants(TR)
.ToDictionary(
TR =方式> int.Parse(tr.Descendants(TD)第一()的InnerText。 ),
TR => int.Parse(tr.Descendants(TD)最近()的InnerText)
)。

如果该HTML将永远是良好的,你可以使用LINQ到XML;该代码将是几乎相同。


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);

解决方案

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.

这篇关于创建字符串在C#字典或列表(包括HTML标记)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆