.html文件> HTMLAgilityPack> TreeView層次結構

c# html html-agility-pack treeview

使用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 Outline 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)

熱門答案

像這樣的東西?

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);
    }
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow