0

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;
}  
8
  • What errors are you getting? Commented Sep 14, 2017 at 12:37
  • Replace <span class="sample_class" id="sample_id"></span> with whatever you want Commented Sep 14, 2017 at 12:38
  • @DaveS No errors, I need to know a way I tried so many way I couldn't complete this Commented Sep 14, 2017 at 12:39
  • @EpicKip i tried like this also but It not getting replacing, stringbuilder.Replace("<span class='sample_class' id='sample_id'></span>", generatedHTMLtable); Commented Sep 14, 2017 at 12:40
  • it does not say placeholder for class and id is empty so that wont work.... Commented Sep 14, 2017 at 12:41

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I have use jquery method encodeURI to encode the string that's what I'm using UrlDecode method, HTML Decode is not working as I am expecting
1

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

4 Comments

Yeah I already said that as a comment but that "din't work" either. So I suggest just leaving it alone
Thanks for your help HTML Agility Pack, Replace is not working as per the my code,I have edit my question @Dave
Can you give some more information? This isn't enough to help. What are you passing in to ReplacePlaceholder?
@DaveS try this "<span class="sample_class" id="sample_id"></span>" in c#
1

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 \

5 Comments

thanks a lot working fine, I tried as you said it's getting replacing
@ShakirAhamed Did you have to change the code in the ReplacePlaceholder() method? When I ran the code above, it outputs System.IO.StringReader, instead of your replaced string
@DaveS I did not, I only tested it with a simple replace as that seemed to be the issue. But what you're noting is a problem too so good thinking!
@ShakirAhamed If it is working fine why did you un-accept, you don't have to accept my answer but I'd like to know?
@EpicKip I un-accept because, I have use different approach to replace the HTML tag, I have added as an answer what I have did so far, But I have up-vote for your answer
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.