HtmlAgilityPack:如何將html元素組合成一個帶有類的標記?

html-agility-pack vb.net

問題:我需要使用HtmlAgilityPack檢查一些HTML元素並組合標記名稱。是否可以從父級到子級提取每個標記,將其替換為具有名稱為“strikeUEmStrong”的類的span。此外,名稱根據HTML元素更改。

事實上,班級名稱的順序確實很重要,我通過反複試驗意識到了這一點。只要它能夠獲得所有元素並將它們組合在一起。它很可能會有多個具有不同格式級別的文本節點。

這會影響多個段落。

例如,如果我有這個HTML代碼:

<p>
<strike><u><em><strong>four styles</strong></em></u></strike></p>

我如何將其轉換為:

<p>
<span class="strikeUEmStrong">four styles</span></p>

它也可以有這種類型的代碼:

<p>
    <strike><u><em><strong>four styles</strong></em></u></strike>&nbsp; <strike><u><em>three styles</em></u></strike></p>
<p>
    <em><strong>two styles</strong></em></p>

輸出應如下所示:

<p>
<span class="strikeUEmStrong">four styles</span>&nbsp; <span class="strikeUEm">three styles<span></p><p><span class="emStrong">two styles<span></p>

原型:

'Retrive the class name of each format node
Function GetClassName(ByVal n As HtmlNode) As String
    Dim ret As String = String.Empty

    If (n.Name <> "#text") And (n.Name <> "p") Then
        ret = n.Name + " "
    End If

    'Get the next node
    For Each child As HtmlNode In n.ChildNodes
        ret &= GetClassName(child)
    Next

    Return ret
End Function

'Create a list of class names
Function GetClassNameList(ByVal classNameList As String) As List(Of String)
    Dim ret As New List(Of String)
    Dim classArr() As String = classNameList.Split(" ")

    For Each className As String In classArr
        ret.Add(className)
    Next

    Return ret
End Function

'Sort a list of class names and return a merged class string
Function GetSortedClassNameString(ByVal classList As List(Of String)) As String

    Dim sortedMergedClass As String = String.Empty

    classList.Sort()

    For Each className As String In classList
        sortedMergedClass &= className
    Next

    Return sortedMergedClass
End Function

'Lets point to the body node
Dim bodyNode As HtmlNode = htmlDoc.DocumentNode.SelectSingleNode("//body")

'Lets create some generic nodes
Dim currPNode As HtmlNode

Dim formatNodes As HtmlNodeCollection

Dim text As String = String.Empty
Dim textSize As Integer = 0

'Make sure the editor has something in it
If editorText <> "" Then

   'Send the text from the editor to the body node
    If bodyNode IsNot Nothing Then
       bodyNode.InnerHtml = editorText
    End If

    Dim pNode = bodyNode.SelectNodes("//p")

    Dim span As HtmlNode = htmlDoc.CreateElement("span")
    Dim tmpBody As HtmlNode = htmlDoc.CreateElement("body")
    Dim textNode As HtmlNode = htmlDoc.CreateTextNode

    Dim pCount As Integer = bodyNode.SelectNodes("//body/p").Count - 1

    For childCountP As Integer = 0 To pCount

        Dim paragraph = HtmlNode.CreateNode(htmlDoc.CreateElement("p").WriteTo)

        'Which paragraph I am at.
        currPNode = pNode.Item(childCountP)

        'For this paragraph get me the collection of html nodes
        formatNodes = currPNode.ChildNodes

        'Count how many Format nodes we have in a paragraph
        Dim formatCount As Integer = currPNode.ChildNodes.Count - 1

       'Go through each node and examine the elements. 
       'Then look at the markup to create classes and then group them under one span
       For child As Integer = 0 To formatCount

           'Iterate through the formateNodes, strike, em, strong, etc.
           Dim currFormatNode = HtmlNode.CreateNode(formatNodes(child).WriteTo)

           'TODO: Handle nested images and links? How do we know what to rip out?

           'First check for format nodes
           'Note, we can't let it use everything because it will change nested elements as well. I.E. span within span.
           If (currFormatNode.Name <> "#text") And (currFormatNode.Name = "strike") Or (currFormatNode.Name = "em") _
               Or (currFormatNode.Name = "strong") Or (currFormatNode.Name = "u") Or (currFormatNode.Name = "sub") _
               Or (currFormatNode.Name = "sup") Or (currFormatNode.Name = "b") Then

              'strip all tags, just take the inner text
              span.InnerHtml = currFormatNode.InnerText

              'Create a text node with text from the lowest node
              textNode = htmlDoc.CreateTextNode(span.InnerText)

              'Recursively go through the format nodes
              'Create a list from the string
              'Then sort the list and return a string
              'Appending the class to the span
               span.SetAttributeValue("class", GetSortedClassNameString(GetClassNameList(GetClassName(currFormatNode).Trim())))

              'Attach the span before the current format node
              currFormatNode.ParentNode.InsertBefore(span, currFormatNode)

             'Remove the formatted children leaving the above node
             currFormatNode.ParentNode.ChildNodes.Remove(currFormatNode)

             'We need to build a paragraph here
             paragraph.InnerHtml &= span.OuterHtml

             'Lets output something for debugging
             childNodesTxt.InnerText &= span.OuterHtml

             Else 'handle #text and other nodes seperately
                  'We need to build a paragraph here
                  paragraph.InnerHtml &= span.OuterHtml
                  textNode = htmlDoc.CreateTextNode(currFormatNode.InnerHtml)

                  'Lets output something for debugging
                  childNodesTxt.InnerText &= textNode.OuterHtml
             End If

        Next
        'End of formats

        'Start adding the new paragraph's to the body node
        tmpBody.AppendChild(paragraph)
     Next
     'End of paragraphs

    'Clean out body first and replace with new elements
    htmlDoc.DocumentNode.SelectSingleNode("//body").Remove()

    'Update our body
    htmlDoc.DocumentNode.SelectSingleNode("//html").AppendChild(tmpBody)

 End If

 htmlDoc.Save(Server.MapPath("html\editor.html"))
 End If

輸出:

<span class="strikeuemstrong">four styles</span>

在我修正了訂購問題之後,最終得到了正確的輸出。感謝您的幫助。

一般承認的答案

這不是一個直截了當的問題。我將描述如何編寫算法來執行此操作,並包含一些偽代碼來幫助。

  1. 我得到了我的父標籤。我假設您要為所有“p”標籤執行此操作
  2. 我會迭代我的子標籤,獲取標籤名稱並將其附加到類名稱中
  3. 我會遞歸迭代孩子,直到我得到我的附加標籤名稱

偽代碼。請原諒任何錯別字,因為我正在打電話。

public string GetClassName(Node n)
{
var ret = n.TagName;

foreach(var child in n.ChildNodes)
{
ret += GetClassName(child);
}

return ret;
}


foreach(var p in paragraphs)
{
foreach(var child in p.ChildNodes)
{
 var span = new Span();
 span.InnerText = child.InnerText; // strip all tags, just take the inner text

span.ClassName = GetClassName(child);

child.ReplaceWith(span); // note: if you do this with a FOREACH and not a for loop, it'll blow up C# for modifying the collection while iterating.  Use for loops. if you're going to do "active" replacement like in this pseudo code
}
}

一旦我獲得更多上下文,我很樂意修改我的答案。如果您需要我改進我的建議,請查看我的建議並對其進行評論。如果沒有,我希望這能得到你所需要的:)



許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因