我有这样的代码
foreach (var table in doc.DocumentNode.SelectNodes("//table[@id='formTbl']"))
{
foreach (var row in table.SelectNodes("tbody/tr"))
{
foreach (var cell in row.SelectNodes("td"))
{
if (X == 1)
{
Console.WriteLine($"Value: {cell.InnerText}");
X = 2;
string Value = cell.InnerText;
}
else if(X==2)
{
Console.WriteLine($"Column: {cell.InnerText}");
X = 1;
string Column = cell.InnerText;
}
}
}
}
我想要得到Json,比如{Column:Value, Column:Value, Column:Value}
我正在使用Newtonsoft。Json,HtmlAgilityPack。有办法得到Json吗?到目前为止,我认为我可以创建{ {X = Column, Y= Value}, {X = Column, Y= Value} }
,但这不是我想要的。
E:表看起来像
<table>
<tr>
<td>Column1</td>
<td>Value1</td>
</tr>
<tr>
<td>Column2</td>
<td>Value2</td>
</tr>
<tr>
<td>Column3</td>
<td>Value3</td>
</tr>
<tr>
<td>Column4</td>
<td>Value4</td>
</tr>
</table>
提供您的"名称是唯一的,您可以简单地使用Dictionary并序列化它。即:
void Main()
{
var html =
@"<table id='formTbl'>
<tbody>
<tr>
<td>Column1</td>
<td>Value1</td>
</tr>
<tr>
<td>Column2</td>
<td>Value2</td>
</tr>
<tr>
<td>Column3</td>
<td>Value3</td>
</tr>
<tr>
<td>Column4</td>
<td>Value4</td>
</tr>
</tbody>
</table>";
var doc = new HtmlDocument();
doc.LoadHtml(html);
Dictionary<string, object> myDict = new Dictionary<string, object>();
foreach (var table in doc.DocumentNode.SelectNodes("//table[@id='formTbl']"))
{
foreach (var row in table.SelectNodes("tbody/tr"))
{
var cells = row.SelectNodes("td");
myDict.Add(cells[0].InnerText, cells[1].InnerText);
}
}
var json = JsonConvert.SerializeObject(myDict, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
编辑:输出:
{
"Column1": "Value1",
"Column2": "Value2",
"Column3": "Value3",
"Column4": "Value4"
}