Reputation: 667
I made a program that modifies a local html page and replaces a certain value in it as you can see here:
string j = Microsoft.VisualBasic.Interaction.InputBox("Replace " + listView2.SelectedItems[0].Text + "/" + intlstv2.ToString() + " With?");
var links = webBrowser1.Document.GetElementsByTagName("td");
foreach(HtmlElement lnk in links)
{
if (lnk.GetAttribute("className") == "point" && lnk.InnerText == listView2.SelectedItems[0].Text || lnk.GetAttribute("className") == "point tekort" && lnk.InnerText == listView2.SelectedItems[0].Text)
{
MessageBox.Show(lnk.InnerText);
MessageBox.Show("Replacing with: " + j.ToString());
System.IO.File.WriteAllText("Fin.html", this.webBrowser1.DocumentText);
System.IO.File.WriteAllText("Fin.html", System.IO.File.ReadAllText("Fin.html").Replace(lnk.InnerText, j));
}
}
And in the html file:
<td class="point">14,5</td> <---- Value that I want replaced
<td class="average" title="Med">14,5</td> <---- Value that I want to keep
The value selected in listview 2 = 14,5 but the problem I'm having is that in the html, 14,5 exists twice (once for the class name point and the second for the class name med) I would only like to replace the innertext of classname point without changing the med's innertext.
How would I do this?
Upvotes: 1
Views: 81
Reputation: 15794
You could find better success by traversing the HTML document as an object tree rather than a "blob" of string.
That being said, using HtmlDocument
to do this will be painful as it doesn't offer a way to introspect easily by class name, attribute values, etc. That being said, you could call GetElementByTagName
and fetch all the td
elements, and filter these by the class
attribute. A bit of complexity, but I guess manageable.
I usually use the HtmlAgilityPack
library, which provides many, many more methods and objects which will allow you to find your html elements with greater ease. Strongly recommend you use it!
Upvotes: 4