C# 將 HTML Table 字串轉為物件 (Deserialize HTML Tables Into Data Model)

2023-02-10

筆記如何將 HTML Table 字串轉為 C# 物件。

logo

說明

class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(@"
            <table>
                <tr>
                    <td>Name</td>
                    <td>Age</td>
                </tr>
                <tr>
                    <td>John Doe</td>
                    <td>30</td>
                </tr>
                <tr>
                    <td>Jane Doe</td>
                    <td>25</td>
                </tr>
            </table>");

        var employees = doc.SelectNodes("//tr")
                            .Cast<XmlNode>()
                            .Skip(1)
                            .Select(tr => new Employee
                            {
                                Name = tr.ChildNodes[0].InnerText,
                                Age = int.Parse(tr.ChildNodes[1].InnerText)
                            });

        var json = JsonConvert.SerializeObject(employees);
        var deserializedEmployees = JsonConvert.DeserializeObject<Employee[]>(json);

        foreach (var employee in deserializedEmployees)
        {
            Console.WriteLine($"Name: {employee.Name}, Age: {employee.Age}");
        }
    }
}