2017-05-04 53 views
1

我有1000多个包含html图像标签的数据库条目。替换html图像标签内的属性

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

一个典型的数据库条目看起来像这样(图像标记的量而改变从输入到输入):

<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” &“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

你应该能够只设置该属性的值:

doc.DocumentNode.OuterHtml 

'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