使用HTMLAgilityPack将节点附加到内部文本

时间:2013-09-23 06:24:13

标签: c# html-agility-pack

问题:我需要删除所有<p>标记的样式属性,如果它包含font-weight:bold属性,则向其添加<b>

例如:如果html是 <p style="margin-top:0pt; margin-bottom:0pt;font-weight:bold; font-weight:bold;font-size:10pt; font-family:ARIAL" align="center"> SOME TEXT HERE</p>

输出应为: <p align="center"> <b>SOME TEXT HERE</b></p>

我正在使用以下代码,

var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(htmlPage);
            foreach (var htmlTag in attributetags)
            {
                var Nodes = htmlDocument.DocumentNode.SelectNodes("//p");
                if (Nodes != null)
                {
                    bool flag = false;
                    foreach (var Node in Nodes)
                    {
                        if (Node.Attributes["style"] != null)
                        {
                            if (Node.Attributes["style"].Value.Contains("font-weight:bold"))
                            {                                    
                               var bnode = HtmlNode.CreateNode("<b>");
                               Node.PrependChild(bnode);
                            }
                            Node.Attributes.Remove("style");                            
                        }
                    }
                }
            }

我也试过了Node.InsertAfter(bcnode, Node), Node.InsertBefor(bnode, Node)

1 个答案:

答案 0 :(得分:6)

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
// select all paragraphs which have style with bold font weight
var paragraphs = doc.DocumentNode.SelectNodes("//p[contains(@style,'font-weight:bold')]");
foreach (var p in paragraphs)
{
    // remove bold font weight from style
    var style = Regex.Replace(p.Attributes["style"].Value, "font-weight:bold;?", "");        
    p.SetAttributeValue("style", style); // assign new style
    // wrap content of paragraph into b tag
    var b = HtmlNode.CreateNode("<b>");
    b.InnerHtml = p.InnerHtml;
    p.ChildNodes.Clear();
    p.AppendChild(b);
}

如果您愿意,可以在一行中包装段落的内容:

p.InnerHtml = HtmlNode.CreateNode("<b>" + p.InnerHtml + "</b>").OuterHtml;