2012-04-18 72 views
0

我已经给了一个工作,以表格格式旧数据转换为新格式。解析HTML文档中的表格并提取TR和TD。与HTML敏捷包

老哑数据如下:

<table> 
<tr> 
<td>Some text 1.</td> 
<td>Some text 2.</td> 
</tr> 
..... //any number of TRs goes here 
</table> 

的问题是,新的数据需要在以下格式:

一些文本1 - 一些文本2. ....

这里需要做什么的总结:

查找表中的所有TR。对于每个TR找到第一个TD并与由“ - ”分隔的第二个TD连接。

我在VB.Net中使用HTML Agility Pack。

请帮忙。

感谢和问候。

回答

0

您可以使用Linq和HtmlAgilityPack从表节点获取所有td,获取此节点的所有InnerText并创建新的TR/TD。

// tableNode is the <table> HtmlNode. If you know where is this table you can use XPath to find him. 

Dim sb As New StringBuilder() 
For Each childNode As HtmlNode In tableNode.DescendantNodes().Where(Function(n) n.Name = "td") 
    sb.Append(String.Format("{0} - ", childNode.InnerText)) 
Next 

tableNode.RemoveAllChildren() 

Dim newTrNode As HtmlNode = tableNode.OwnerDocument.CreateElement("tr") 
Dim newTdNode As HtmlNode = tableNode.OwnerDocument.CreateElement("td") 

newTdNode.InnerHtml = sb.ToString() 
newTrNode.AppendChild(newTdNode) 

tableNode.AppendChild(newTrNode) 

我希望它能帮助