Shakir Ahamed
Shakir Ahamed

Reputation: 1308

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. 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

<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;
}  

Upvotes: 0

Views: 8231

Answers (4)

Shakir Ahamed
Shakir Ahamed

Reputation: 1308

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.

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

Upvotes: 0

Dave S
Dave S

Reputation: 1423

You are calling ToString() on the StringReader and trying to return that. In this case, that will return a string containing the name of the type (System.IO.StringReader). You don't need the StringReader at all, calling ToString() on the StringBuilder will output the string you are looking for.

However, since all you are doing is a string replacement, you don't need the StringBuilder anyway.

Also, as EricKip mentioned in his answer, the string passed to the Replace method does is not using the correct quotation marks.

This is a working version of your ReplacePlaceHolder method.

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. However, it is used for decoding URLs, which probably isn't what you need. You might be looking for HTML Decode

Upvotes: 2

EpicKip
EpicKip

Reputation: 4033

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 \

Upvotes: 1

Dave S
Dave S

Reputation: 1423

It looks like your code is trying to replace a span with the CSS class placeholder

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

but your question states that you want to replace the element with the 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. There are options using the framework, or you might want to look at something like HTML Agility Pack

Upvotes: 1

Related Questions