0

使用 HTMLAgilityPack + TreeView 创建 HTML 文件的层次结构 GUI。HTML 文件是由 CMS 生成的,而且生成得不是很好。

需要做到以下几点: 1. 将每个Outline Level 0节点读入 TreeView。

HtmlNodeCollection ZeroLevelNodes = doc.DocumentNode.SelectNodes("//body/object[@type='text/sitemap']|//body/ul/object[@type='text/sitemap']|//body/ul/li/object[@type='text/sitemap']");

2. 将 Outline Level 1 节点读取为它们各自 Outline Level 0 节点的子节点 注意:每个 Outline Level 0 节点(减去一些对这个问题不重要的节点)的布局为<li><object><param /></object>(注意缺少结束</li>标记) . 需要在 TreeView 中显示为子节点的节点将位于无序列表<ul>中,该列表是 0 级节点标记的下一个兄弟节点<li>,例如:

<ul>
    <li>
        <object>
            <param name="**exampleLevel0**" value="**example.htm**" /> //value example.htm as the text in the level 0 node.
        </object>
    <ul>
        <li>
            <object>
               <param name="**ExampleLevel1**" value="childnode.htm" /> //childnode.htm as the text in the level 1 child node.
            </object>
        <li>
            <object>
               <param name="**ExampleLevel1_2**" value="childnode2.htm" /> //childnode2.htm as the text in the level 1 child node.
            </object>
    </ul>
 </ul>

这是我当前生成顶层层次结构的代码

HtmlNodeCollection tocNodes = doc.DocumentNode.SelectNodes("//body/object[@type='text/sitemap']|//body/ul/object[@type='text/sitemap']|//body/ul/li/object[@type='text/sitemap']");
foreach (HtmlNode zeroLevelNode in zeroLevelNodes)
        {

            TreeNode tNode = new TreeNode();
            HtmlNode paramNode = zeroLevelNode.SelectSingleNode("param[@name]");
            string paramName = paramNode.GetAttributeValue("name", null);
            string paramValue = paramNode.GetAttributeValue("value", null);
            TreeView.Nodes.Add(new TreeNode(paramValue));
            tNode = TreeView.Nodes[i];
            AddNode(zeroLevelNode, tNode);
            i += 1;
        }

谁能帮我将“孩子”(大纲级别 1)节点加载到 TreeView 所需的代码?(AddNode(zeroLevelNode, tNode)

4

1 回答 1

2

像这样的东西?

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
TreeNode root = new TreeNode("HTML");
treeView1.Nodes.Add(root);

LoadTree(root, doc.DocumentNode);


void LoadTree(TreeNode treeNode, HtmlAgilityPack.HtmlNode rootNode)
{
    foreach (var node in rootNode.ChildNodes.Where(n=>n.Name!="#text"))
    {
        TreeNode n = new TreeNode(node.Name);
        node.Attributes.Select(a => a.Name + "=" + a.Value)
                       .ToList()
                       .ForEach(x => n.Nodes.Add(x));
        treeNode.Nodes.Add(n);

        LoadTree(n, node);
    }
}
于 2012-07-09T17:13:09.350 回答