【发布时间】:2014-07-06 13:35:09
【问题描述】:
我对这个有点难过。我有一些 html,其中包含图像,然后是一些文本。但我需要重新排列 html,以便首先显示图像 - 所以图像,然后是 h3 标记,然后是文本。
编辑:下面的代码实际上并没有删除样式属性。我认为它正在工作,直到我更仔细地查看了 html 源代码。所以我需要帮助来剥离给定的样式属性
<p>
<img alt="" src="../../../../images/PeterDoocy5.jpg" style="width: 608px; height: 316px;" /></p>
到目前为止,我已经设法使用 HAP 去除页面中图像的样式属性:
<Extension()> Public Function RemoveStyleAttributes(input As String)
Dim cleint As New WebClient
Dim html As New HtmlDocument
html.LoadHtml(input)
Dim elementsWithStyleAttribute = html.DocumentNode.SelectNodes("//@img")
If elementsWithStyleAttribute IsNot Nothing Then
For Each element In elementsWithStyleAttribute
element.Attributes("style").Remove()
Next
End If
Return input
End Function
但是我不知道如何将图像拉到 H3 标签的前面。
HTML:
<div class="col-md-6">
<div class="item">
<div class="content galleryItem">
<h3>
DOJ court docs in Abu Khattallah case dispel Obama Admin narrative about the anti-Islam video
</h3>
<p>
<img alt="" class="img-responsive" src="../../../../images/AbuKhattala.jpg" />
</p>
<p>
But it was an awful, disgusting video.....
</p>
</div>
</div>
</div>
现在的扩展方法:
<Extension()> Public Function RemoveStyleAttributes(html As HtmlDocument)
Dim divs = html.DocumentNode.SelectNodes("//div[@class='content galleryItem']")
For Each div As HtmlNode In divs
'get <img> and remove its style attribute'
Dim img = div.SelectSingleNode("./p/img[@style]")
img.Attributes("style").Remove()
'remove <h3> and <p>text here</p>'
Dim h3 = div.SelectSingleNode("./h3")
h3.Remove()
Dim text = div.SelectSingleNode("./p[not(img)]")
text.Remove()
'add <h3> and <p>text here</p> to the parent again in desired order'
div.AppendChild(h3)
div.AppendChild(text)
Next
Return html.DocumentNode.OuterHtml.ToString
End Function
尝试将其用作@Html.Raw(item.PostSummary.RemoveStyleAttributes)
【问题讨论】:
标签: html asp.net-mvc vb.net html-agility-pack