简体   繁体   English

用于在C#中替换div的简单代码

[英]Simple code for replace a div in C#

I have a problem. 我有个问题。 I learn to edit html document in a simple program in C#, but i have a question. 我学会了用C#在一个简单的程序中编辑html文档,但是我有一个问题。

i have a line code in HTML like that: 我有这样的HTML代码:

<div role = "banner" class = "TopBanner">

I want to change this line code in this: 我要在此更改此行代码:

<div role = "banner" class = "TopBanner" style = "display:none;">

i try to use 我尝试使用

        HtmlElementCollection ElemCol= default(HtmlElementCollection);
        ElemCol= webBrowser.Document.GetElementsByTagName("div");
        foreach (HtmlElement curElement in ElemCol)
        {
            if (curElement.OuterHtml.Contains("TopBanner"))
            {
                curElement.Style = "display:none";
            }
        }

but is not working. 但不起作用。 my code just set display to none and don't replace the div with new text. 我的代码只是将display设置为none并且不将div替换为新文本。 Any ideas to replace the div? 有什么想法取代div吗?

Try this code: 试试这个代码:

HtmlElementCollection ElemCol= default(HtmlElementCollection);
ElemCol= webBrowser.Document.GetElementsByTagName("div");
foreach (HtmlElement curElement in ElemCol)
{
    if (curElement.GetAttribute("class").Contains("TopBanner"))
    {
        curElement.SetAttribute("style", "display:none");
    }
}

Try using SetAttribute 尝试使用SetAttribute

       if (curElement.OuterHtml.Contains("TopBanner"))
       {
                curElement.SetAttribute("style", "display:none");= "";
       }

我想你想使用setAttribute

curElement.setAttribute("style", "display:none")

If it's something you do a lot in your program (HTML manipulation), you may want to look at a project like CsQuery . 如果您在程序中做了很多事情(HTML操作),则可能需要查看CsQuery之类的项目。 It may give you much better control over stuff like this. 它可以使您更好地控制此类内容。 If it's only something done a few times, a full assembly may be overkill. 如果只做几次,那么完整的组装可能就太过分了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM