You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用HtmlAgilityPack解析HTML表格 Newtonsoft.Json生成自定义键值JSON

解决方案

实现思路

  • 你的表格结构每行固定2个<td>,第一个为键名,第二个为对应值,无需按单元格遍历做状态判断,直接按行读取即可
  • 使用Dictionary<string, string>存储键值对,Newtonsoft.Json序列化字典时会直接生成{"键":"值"}格式的JSON对象,正好匹配你的需求
  • 增加空节点判断,避免节点不存在时抛出空引用异常

调整后完整代码

using HtmlAgilityPack;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

// 此处保留你原有加载HtmlDocument的逻辑,例如doc.LoadHtml(html文本)
var resultDict = new Dictionary<string, string>();

// 匹配id为formTbl的表格,如果实际table没有嵌套tbody标签,把XPath里的tbody/去掉即可
foreach (var table in doc.DocumentNode.SelectNodes("//table[@id='formTbl']") ?? Array.Empty<HtmlNode>())
{
    foreach (var row in table.SelectNodes("tbody/tr") ?? Array.Empty<HtmlNode>())
    {
        var cells = row.SelectNodes("td");
        // 跳过单元格不足2个的无效行
        if (cells == null || cells.Count < 2) 
            continue;
        
        string columnName = cells[0].InnerText.Trim();
        string value = cells[1].InnerText.Trim();
        
        if (!string.IsNullOrEmpty(columnName))
        {
            // 重复列名默认覆盖,可根据需求调整为追加后缀等逻辑
            resultDict[columnName] = value;
        }
    }
}

// 序列化得到目标格式JSON
string outputJson = JsonConvert.SerializeObject(resultDict, Formatting.Indented);
Console.WriteLine(outputJson);

输出示例

运行后生成的JSON完全符合预期:

{
  "Column1": "Value1",
  "Column2": "Value2",
  "Column3": "Value3",
  "Column4": "Value4"
}

内容的提问来源于stack exchange,提问作者Justyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:12:02