我从不久前的帖子中找到了一个代码片段。由于我是 C# 的初学者,我有点迷路了。
我正在尝试从表中提取所有单元格并将它们写入一个看起来像这样的 XML 文件
<?xml version="1.0" encoding="utf-8"?>
<Stats Date="11/4/2013">
<Player Rank="1">
<Name>P.K. Subban</Name>
<Team>MTL</Team>
<Pos>D</Pos>
<GP>15</GP>
<G>3</G>
<A>11</A>
<Pts>14</Pts>
<PlusMinus>+2</PlusMinus>
<PIM>16</PIM>
<PP>2</PP>
<SH>0</SH>
<GW>0</GW>
<OT>0</OT>
<Shots>47</Shots>
<ShotPctg>6.4</ShotPctg>
<TOIPerGame>24:29</TOIPerGame>
<ShiftsPerGame>27.3</ShiftsPerGame>
<FOWinPctg>0.0</FOWinPctg>
</Player>
</Stats>
我的问题是我不知道如何遍历 25 行 19 列的整个表格。我只能从整个表中提取 1 行。
这就是我所拥有的(我已经获取了片段并修改了 elementNames 和 Xpath
public void ParseHtml()
{
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(Source);
var cells = htmlDoc.DocumentNode
.SelectNodes("//table[@class='data stats']/tbody/tr/td")
.Select(node => node.InnerText.Trim())
.ToList();
var elementNames = new[] { "Name", "Team", "Pos", "GP", "G", "A", "Pts", "PlusMinus", "PIM", "PP", "SH", "GW", "OT", "Shots", "ShotPctg", "TOIPerGame", "ShiftsPerGame", "FOWinPctg" };
var xmlDoc = new XElement("Stats", new XAttribute("Date", DateTime.Now.ToShortDateString()),
new XElement("Player", new XAttribute("Rank", cells.First()),
cells.Skip(1)
.Zip(elementNames, (Value, Name) => new XElement(Name, Value))
.Where(element => !String.IsNullOrEmpty(element.Value))
)
);
xmlDoc.Save("parsed.xml");
}
我尝试过的事情:改变
var cells = htmlDoc.DocumentNode
.SelectNodes("//table[@class='data stats']/tbody/tr/td")
.Select(node => node.InnerText.Trim())
.ToList();
至
foreach (HtmlNode cells in htmlDoc.DocumentNode
.SelectNodes("//table[@class='data stats']/tbody/tr/td")
.Select(node => node.InnerText.Trim())
.ToList() )
{
var elementNames....
..
...
通过此更改,我没有得到任何值,并且 xml 节点减少到 2。任何人都可以帮助我吗?我已经尝试了 3 天来解决这个问题。