将节点类型更改为#text,同时使用HtmlAgilityPack保留内部节点

时间:2009-12-29 22:18:16

标签: c# .net html html-agility-pack

我正在使用HtmlAgilityPack来解析我正在转换为HTML的XML文件。某些节点将转换为HTML等效节点。在保持内容的同时,我需要删除其他不需要的内容。我尝试将它转换为#text节点而没有运气。这是我的代码:

private HtmlNode ConvertElementsPerDatabase(HtmlNode parentNode, bool transformChildNodes)
{
    var listTagsToReplace = XmlTagMapping.SelectAll(string.Empty);  // Custom Dataobject
    var node = parentNode;
    if (node != null)
    {
        var bNodeFound = false;
        if (node.Name.Equals("xref"))
        {
            bNodeFound = true;
            node = NodeXref(node);
        }
        if (node.Name.Equals("graphic"))
        {
            bNodeFound = true;
            node = NodeGraphic(node);
        }
        if (node.Name.Equals("ext-link"))
        {
            bNodeFound = true;
            node = NodeExtLink(node);
        }

        foreach (var infoTagToReplace in listTagsToReplace)
        {
            if (node.Name.Equals(infoTagToReplace.XmlTag))
            {
                bNodeFound = true;
                node.Name = infoTagToReplace.HtmlTag;
                if (!string.IsNullOrEmpty(infoTagToReplace.CssClass))
                    node.Attributes.Add("class", infoTagToReplace.CssClass);

                if (node.HasAttributes)
                {
                    var listTagAttributeToReplace = XmlTagAttributeMapping.SelectAll_TagId(infoTagToReplace.Id); // Custom Dataobject
                    for (int i = 0; i < node.Attributes.Count; i++ )
                    {
                        var bDeleteAttribute = true;
                        foreach (var infoTagAttributeToReplace in listTagAttributeToReplace)
                        {
                            if (infoTagAttributeToReplace.XmlName.Equals(node.Attributes[i].Name))
                            {
                                node.Attributes[i].Name = infoTagAttributeToReplace.HtmlName;
                                bDeleteAttribute = false;
                            }
                        }
                        if (bDeleteAttribute)
                            node.Attributes.Remove(node.Attributes[i].Name);
                    }
                }
            }
        }
        if (transformChildNodes)
            for (int i = 0; i < parentNode.ChildNodes.Count; i++)
                parentNode.ChildNodes[i] = ConvertElementsPerDatabase(parentNode.ChildNodes[i], true);

        if (!bNodeFound)
        {
            // Replace with #text
        }
    }
    return parentNode;
}

最后,我需要进行节点替换(如果找不到节点,则会看到“替换为#text”注释)。我整天都在撕开我的头发(剩下的东西),这可能是愚蠢的。我无法获得编译帮助,也没有在线版本。帮助Stackoverflow!你是我唯一的希望。 ; - )

1 个答案:

答案 0 :(得分:0)

我认为你可以这样做:

return new HtmlNode(HtmlNodeType.Text, parentNode.OwnerDocument, 0);

这当然会将节点添加到文档的头部,但我假设您有一些代码来处理文档中应该添加节点的位置。

关于文档注释,Html Agility Pack documentation的当前(撰写本文时)下载包含一个CHM文件,该文件无需编译即可查看。