从 HTML 字符串创建 HTMLDocument(在 Java 中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6698057/
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
Creating an HTMLDocument from a String of HTML (in Java)
提问by Paul Reiners
I'm working on a method that takes a String of HTML and returns an analogous
我正在研究一种采用 HTML 字符串并返回类似的方法
javax.swing.text.html.HTMLDocument
What is the most efficient way of doing this?
这样做的最有效方法是什么?
The way I'm currently doing this is to use a SAX parser to parse the HTML string. I keep track of when I hit open tags (for example, <i>). When I hit the corresponding close tag (for example, </i>), I apply the italics style to the characters I've hit in between.
我目前这样做的方法是使用 SAX 解析器来解析 HTML 字符串。我会跟踪我何时点击打开的标签(例如,<i>)。当我点击相应的结束标记(例如,</i>)时,我将斜体样式应用于我在中间点击的字符。
This certainly works, but it's not fast enough. Is there a faster way of doing this?
这当然有效,但还不够快。有没有更快的方法来做到这一点?
采纳答案by mouser
Try to use HtmlEditorKit
class. It supports parsing of HTML content that can be read directly from String
(e.g. through StringReader
). There seems to be an articleabout how to do this.
尝试使用HtmlEditorKit
类。它支持解析可以直接从中读取的 HTML 内容String
(例如通过StringReader
)。似乎有一篇关于如何做到这一点的文章。
Edit: To give an example, basically I think it could be done like this (aftrer the code is executed, htmlDoc
should contain the loaded document...):
编辑:举个例子,基本上我认为可以这样做(在代码执行后,htmlDoc
应该包含加载的文档......):
Reader stringReader = new StringReader(string);
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
HTMLEditorKit.Parser parser = new ParserDelegator();
parser.parse(stringReader, htmlDoc.getReader(0), true);
回答by StanislavL
Agree with mouser but a small correction
同意 mouser,但有一点更正
Reader stringReader = new StringReader(string);
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
htmlKit.read(stringReader, htmlDoc, 0);
回答by nfechner
You could try to use the HTMLDocument.setOuterHTML
method. Simply add a random element and replace it afterwards with your HTML string.
您可以尝试使用该HTMLDocument.setOuterHTML
方法。只需添加一个随机元素,然后用您的 HTML 字符串替换它。