I want to read and display a text from my HTML Page into a Label or TextBlock in my WPF application. How do I do that?
With Windows Forms I have done it this way:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("C:\Users\Test\Desktop\Webseite\test.htm")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ImageInhalt As String
Label1.Text = WebBrowser1.Document.GetElementById("mytext").GetAttribute("value")
ImageInhalt = WebBrowser1.Document.GetElementById("mytext2").GetAttribute("value")
If ImageInhalt.Contains("STOP") Then
PictureBox1.Image = My.Resources._stop
End If
End Sub
End Class
HTML Page (test.htm)
<input type="text" name="userInfoNav" value="Hallo"/><br/>"
Many thanks now for the help
CodePudding user response:
You must load the HTML content of an URL or file into a mshtml.HTMLDocument
. You can then process the DOM object in a JavaScript like syntax.
Requires reference to Microsoft.mshtml.dll.
C#
partial class MainWindow : Window
{
private mshtml.HTMLDocument HtmlDocument { get; set; }
public async Task SetTextBoxTextAsync(string filePath, string id)
{
await UpdateHtmlDocumentAsync(filePath);
string value = GetHtmlElementValueById(id);
this.TextBlock.Text = value;
}
private async Task UpdateHtmlDocumentAsync(string filePath)
{
string htmlContent = await File.ReadAllLinesAsync(filePath);
this.HtmlDocument = new HTMLDocument();
(this.HtmlDocument as IHTMLDocument2).write(htmlContent);
}
private string GetHtmlElementValueById(string elementId)
=> this.HtmlDocument.getElementById(elementId).innerText;
}
VB.NET
Partial Class MainWindow
Inherits Window
Private Property HtmlDocument As mshtml.HTMLDocument
Private Async Function SetTextBoxTextAsync(ByVal filePath As String, ByVal id As String) As Task
Await UpdateHtmlDocumentAsync(filePath)
Dim value As String = GetHtmlElementValueById(id)
Me.TextBlock.Text = value
End Function
Public Async Function UpdateHtmlDocumentAsync(ByVal filePath As String) As Task
Dim htmlContent As String = Await File.ReadAllLinesAsync(filePath)
Me.HtmlDocument = New HTMLDocument()
(TryCast(Me.HtmlDocument, IHTMLDocument2)).write(htmlContent)
End Function
Public Function GetHtmlElementValueById(ByVal elementId As String) As String
Return Me.HtmlDocument.getElementById(elementId).innerText
End Function
End Class
Remarks
If you are interested in rendering the content, then use the WebBrowser
control. It has a Document
property that you can cast to a mshtml.HTMLDocument
. Since the WebBrowser
is a heavy instance, you should only use it if your intend is to render the HTML. Otherwise constuct the mshtml.HTMLDocument
manually like shown above.
CodePudding user response:
You can load the html into a TextBlock
like this:
TextBlock1.Text = System.IO.File.ReadAllText("C:\Users\Test\Desktop\Webseite\test.htm")
I assume that the TextBlock
is named: TextBlock1
.