简体   繁体   English

在HTML字符串中查找元素并用C#中的HTML表替换

[英]Find element in HTML string and replace with HTML table in C#

I want to do, Find the html element from HTML string and replace with HTML table, please help to complete my task. 我想做的是,从HTML字符串中找到html元素并替换为HTML表,请帮助完成我的任务。 thanks in advance 提前致谢

I have attach sample HTML and my code behind code, here I want to remove tag with id sample_id in the HTML and add a table to that place in HTML string 我在代码后面附加了示例HTML和我的代码,在这里我想删除HTML中ID为sample_id标签,并在HTML字符串中的该位置添加一个表

 <div class="row"> <div class="col-md-4"> <h2>Getting started</h2> <p> ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and gives you full control over markup for enjoyable, agile development. </p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Get more libraries</h2> <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Web Hosting</h2> <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p> </div> <span class="sample_class" id="sample_id"></span> </div> 

public string ReplacePlaceHolder(string value)
{
     string HTMLToConvert = "";
     StringWriter myWriter = new StringWriter();
     // Decode the encoded string.
     HTMLToConvert = HttpUtility.UrlDecode(value).ToString();

     //HtmlDocument doc = new HtmlDocument();
     //doc.LoadHtml(HTMLToConvert);
     //var nodes = doc.DocumentNode.SelectSingleNode("//span[@class='placeholder']");

     string generatedHTMLtable = GenerateHTMLTable();
     StringBuilder builder = new StringBuilder(HTMLToConvert);

     builder.Replace("<span class='sample_class' id='sample_id'></span>", generatedHTMLtable);
     StringReader sr = new StringReader(builder.ToString());
     return sr.ToString();
}

//Sample method for generating string of HTML table
public string GenerateHTMLTable()
{
    string tableHtml = "";
    DataSet ds = new DataSet();
    DataTable dt = new DataTable("FirstTable");
    dt.Columns.Add(new DataColumn("UserID", typeof(int)));
    dt.Columns.Add(new DataColumn("AccountID", typeof(int)));
    dt.Columns.Add(new DataColumn("Code", typeof(string)));
    dt.Columns.Add(new DataColumn("AccountName", typeof(string)));
    dt.Columns.Add(new DataColumn("GroupCode", typeof(string)));

    for (int i = 0; i < 6; i++)
    {
       DataRow dr = dt.NewRow();
       dr["UserID"] = i;
       dr["AccountID"] = i + 1;
       dr["Code"] = "COD" + i;
       dr["AccountName"] = "Account" + i;
       dr["GroupCode"] = "GRP" + i;
       dt.Rows.Add(dr);
    }
    ds.Tables.Add(dt);

    tableHtml += "<table>";
    tableHtml += "<tr><th>UserID</th><th>AccountID</th><th>Code</th><th>AccountName</th><th>GroupCode</th></tr>";

    foreach (DataRow drAccount in dt.Rows)
    {
        tableHtml += "<tr><td>" + drAccount["UserID"] + "</td><td>" + drAccount["AccountID"] + "</td><td>" + drAccount["Code"] + "</td><td>" + drAccount["AccountName"] + "</td><td>" + drAccount["GroupCode"] + "</td></tr>";
    }
    tableHtml += "</table>";
    return tableHtml;
}  

You are calling ToString() on the StringReader and trying to return that. 您正在StringReader上调用ToString()并尝试返回该值。 In this case, that will return a string containing the name of the type ( System.IO.StringReader ). 在这种情况下,它将返回一个字符串,其中包含类型的名称( System.IO.StringReader )。 You don't need the StringReader at all, calling ToString() on the StringBuilder will output the string you are looking for. 您根本不需要StringReader ,在StringBuilder上调用ToString()将输出您要查找的字符串。

However, since all you are doing is a string replacement, you don't need the StringBuilder anyway. 但是,由于您要做的只是替换字符串,因此无论如何都不需要StringBuilder

Also, as EricKip mentioned in his answer, the string passed to the Replace method does is not using the correct quotation marks. 同样,正如EricKip在他的回答中提到的那样,传递给Replace方法的字符串没有使用正确的引号。

This is a working version of your ReplacePlaceHolder method. 这是您的ReplacePlaceHolder方法的工作版本。

public string ReplacePlaceHolder(string value)
{
    var HTMLToConvert = HttpUtility.UrlDecode(value)       
    return HTMLToConvert.Replace("<span class=\"sample_class\" id=\"sample_id\"></span>", GenerateHTMLTable());
}

Note that I have retained the HttpUtility.UrlDecode() line, as we don't know what your value parameter is, so I don't know if it is needed. 请注意,我保留了HttpUtility.UrlDecode()行,因为我们不知道您的value参数是什么,所以我不知道是否需要它。 However, it is used for decoding URLs, which probably isn't what you need. 但是,它用于解码URL,这可能不是您所需要的。 You might be looking for HTML Decode 您可能正在寻找HTML解码

It looks like your code is trying to replace a span with the CSS class placeholder 看起来您的代码正在尝试用CSS类placeholder替换范围

builder.Replace("<span class='placeholder'></span>", generatedHTMLtable);

but your question states that you want to replace the element with the ID sample_id . 但是您的问题是您要用ID sample_id替换元素。

So, replace the line above with: 因此,将上面的行替换为:

builder.Replace("<span class="sample_class" id="sample_id"></span>", generatedHTMLtable);

Incidentally, string replace isn't going to be a robust way to work with HTML if you want to do anything more complicated. 顺便说一句,如果您想做更复杂的事情,字符串替换将不是使用HTML的可靠方法。 There are options using the framework, or you might want to look at something like HTML Agility Pack 有使用该框架的选项,或者您可能想看看类似HTML Agility Pack的东西

After your edit you edited in this: 编辑后,您在其中进行了编辑:

builder.Replace("<span class='sample_class' id='sample_id'></span>", generatedHTMLtable);

But that isn't the same as: 但这与以下内容不同:

<span class="sample_class" id="sample_id"></span>

The 1st has ' and the second has " to fix this use it like this: 第一个具有' ,第二个具有"来解决此问题,如下所示:

builder.Replace("<span class=\"sample_class\" id=\"sample_id\"></span>", generatedHTMLtable);

This way you can put " inside a string, you're escaping it with \\ 这样,您可以将"放入字符串中,并用\\转义

Hi currently I'm using this approach to complete my task, exactly this is what I want,I'm adding this is because of future user. 您好,目前我正在使用这种方法来完成任务,正是我想要的,我添加这是因为将来的用户。

We can find the element using id or class and replace full element like below. 我们可以使用id或class查找元素,然后替换完整的元素,如下所示。

string ofRegex = "<span (class|id)=\"{0}\".*?>\\w*\\n";  // here I have added span tag, we can use any kind of HTML tag which is we need to replace
string finalRegex = string.Format(ofRegex, "sample_class"); // generating regex with class name

string generatedHTMLtable = GenerateHTMLTable();         //// Populate HTML table
htmlAfterREplace = Regex.Replace(HTMLToConvert, finalRegex, generatedHTMLtable);         ///Replace with generated table using rege

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

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