开发者

C# How to add custom attributes to html string?

I have string contains html and i want to add to some attributes to that html string.

Is there any html parser/editor class in .NETi can use to do that?

For example i have tags <script> in that html and i want to add attribute src="somesrtpath" to all of them.

I would have probabl开发者_开发知识库y just have one case where html would contain just two script tags in the beginning something like

 <script type="text/javascript" `<add hrere src>` >
 </script>
 <script type="text/javascript" `<add hrere src>`>
 </script>

Basically what i would want to do is just to say to some function - here is html for each script tag add this src


if your HTML is in a string you surely can parse it and manipulate it with the:

HTML Agility Pack, plenty, really, plenty of examples here in SO...


If you are getting the HTML as a string then you could use .IndexOf("<script ") to find the scripts.

for (int scriptStart = htmlContent.IndexOf("<script "); scriptStart > -1; scriptStart = htmlContent.IndexOf("<script ",  scriptStart + 1))
{
    // Find position of the type= bit.
    int typeAttributeIndex = htmlContent.IndexOf("type=\"text/javascript\"", scriptStart);

    htmlContent.Insert(typeAttributeIndex + 22, " src=\"something\"");
}

This is a bit quick and dirty. If you want to clean it up a bit more you could use a regular expression to make sure you are matching the script tag correctly. You could also match the end of the script block looking for the > but just be aware that script tags can be <script ... ></script> or sometimes <script ... />. Putting the src after the / would cause an issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜