vba MSHTML:CreateDocumentFromString 而不是 CreateDocumentFromUrl
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9995257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MSHTML: CreateDocumentFromString instead of CreateDocumentFromUrl
提问by mwolfe02
I'd like to use the MSHTML library to parse some HTML that I have in a string variable. However, I can't figure out how to do this. I can easily parse the contents of a webpage given a known URL, but not the source HTML directly. Is this possible? If so, how?
我想使用 MSHTML 库来解析字符串变量中的一些 HTML。但是,我无法弄清楚如何做到这一点。我可以轻松解析给定已知 URL 的网页内容,但不能直接解析源 HTML。这可能吗?如果是这样,如何?
Public Sub ParseHTML(sHTML As String)
Dim oHTML As New HTMLDocument, oDoc As HTMLDocument
'This works:'
Set oDoc = oHTML.createDocumentFromUrl("http://www.google.com", "")
'I would like to do the following but no such method actually exists:'
Set oDoc = oHTML.createDocumentFromString(sHTML)
....
'Parse the HTML using the oDoc variable'
....
回答by Alex K.
You can;
你可以;
Dim odoc As Object
Set odoc = CreateObject("htmlfile") '// late binding
'// or:
'// Set odoc = New HTMLDocument
'// for early binding
odoc.open
odoc.write "<p> In his house at R'lyeh, dead <b>Cthulhu</b> waits dreaming</p>"
odoc.Close
MsgBox odoc.body.outerHTML
回答by bboyse
This is a much better example. You will not get a null exception, nor late binding.
这是一个更好的例子。你不会得到空异常,也不会延迟绑定。
(And if you use WPF, just add System.Windows.Forms
in your reference.)
(如果您使用 WPF,只需添加System.Windows.Forms
您的参考。)
Dim a As Object
a = New mshtml.HTMLDocument
a.open()
a.writeln(code)
a.close()
Do Until a.readyState = "complete"
System.Windows.Forms.Application.DoEvents()
Loop
Dim doc As mshtml.HTMLDocument = a
Dim b As mshtml.HTMLSelectElement = doc.getElementsByTagName("Select").item("lang", 0)
回答by user3305711
For straight HTML code such as Access-Rich-Text this does it:
对于像 Access-Rich-Text 这样的直接 HTML 代码,这样做:
Dim HTMLDoc As New HTMLDocument
HTMLDoc.Body.innerHTML = strHTMLText