替换html图像标记中的属性

时间:2017-05-04 16:29:54

标签: vb.net html-agility-pack

我有1000多个包含html图像标记的数据库条目。

问题是,90%的'src'属性只是占位符。我需要用适当的实际来源替换所有这些占位符。

典型的数据库条目如下所示(图像标记的数量因条目而异):

<p>A monster rushes at you!</p>
Monster:<p><img id="d8fh4-gfkj3" src="(image_placeholder)" /></p>
<br />
Treasure: <p><img id="x23zo-115a9" src="(image_placeholder)" /></p>
Please select your action below:
</br />

使用上面图片代码中的ID,'d8fh4-gfkj3'&amp; 'x23zo-115a9',我可以查询另一个函数来获取这些图像的“真实”来源。

所以我尝试使用HtmlAgilityPack并提出了这个(下面):

    Dim doc As New HtmlDocument()
    doc.LoadHtml(encounterText)

    For Each imgTag As HtmlNode In doc.DocumentNode.SelectNodes("//img")
        'get the ID
        Dim imgId As HtmlAttribute = imgTag.Attributes("id")
        Dim imageId As String = imgId.Value

        'get the new/real path
        Dim newPath = getMediaPath(imageId)
        Dim imgSrc As HtmlAttribute = imgTag.Attributes("src")

        'check to see if the <img> tag "src" attribute has a placeholder
        If imgSrc.Value.Contains("(image_placeholder)") Then
            'replace old image src attribute with 'src=newPath'
        End If
    Next

但我无法弄清楚如何用新值替换旧值。

有没有办法用HtmlAgilityPack做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:1)

您应该只能设置属性的值:

'check to see if the <img> tag "src" attribute has a placeholder
If imgSrc.Value.Contains("(image_placeholder)") Then
    'replace old image src attribute with 'src=newPath'
    imgSrc.Value = newPath
End If

替换后,您可以使用以下命令获取更新的HTML:

doc.DocumentNode.OuterHtml