我将提取一些HTML文件的背景并用新值替换它们。
为了控制 BODY 标签是否在其样式中定义了背景,我在下面的代码中使用了css:
foreach (HtmlNode bodyNode in doc.DocumentNode.SelectNodes("//body"))
{
if (bodyNode.Attributes.Contains("style") && bodyNode.Attributes["style"].Value.Replace(" ","").Contains("background-image:url"))
{
//code to replace background-url
}
}
我的问题是如何从样式属性中的此类标记中检索background-url值:
<body style="background-image: url('test/bg.jpg')" >
并将其替换为新值,如下所示:
<body style="background-image: url('new value')" >
答案 0 :(得分:1)
您可以删除旧样式并添加新样式,例如:
bodyNode.Attributes.Remove("style");
bodyNode.Attributes.Add("style", "width:95%;background-image: url('test/bg1.jpg');font-size:xx-large;text-align:center");
答案 1 :(得分:1)
请尝试以下代码。 使用正则表达式提取背景图像URL(括号中的字符串)并将其替换为新图像。 现在删除样式属性并添加新的(带有替换图像的样式)。
这适用于所有属性值和格式。
foreach (HtmlNode bodyNode in doc.DocumentNode.SelectNodes("//body"))
{
string newImg = "new-value.png";
if (bodyNode.Attributes.Contains("style") && bodyNode.Attributes["style"].Value.Contains("background-image:url"))
{
string style = bodyNode.Attributes["style"].Value;
string oldImg = Regex.Match(style, @"(?<=\().+?(?=\))").Value;
string oldStyle = bodyNode.Attributes["style"].Value;
string newStyle = oldStyle.Replace(oldImg, newImg);
bodyNode.Attributes.Remove("style");
bodyNode.Attributes.Add("style", newStyle);
}
}