java – JSoup – 格式化元素
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – JSoup – 格式化元素,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2156字,纯文字阅读大概需要4分钟。
内容图文
![java – JSoup – 格式化元素](/upload/InfoBanner/zyjiaocheng/727/dde03240f7bf4a59ae7885fdb5a8f23f.jpg)
假设我有这个HTML:
<html>
<head>
</head>
<body>
<form method="post">
<select name="books">
<option value="111">111</option>
<option value="222">222</option>
</select>
</form>
</body>
</html>
我在Jsoup中加载它并获得结果:
Document doc = Jsoup.parse(html);
doc.outputSettings().indentAmount(4);
doc.outputSettings().charset("UTF-8");
doc.outputSettings().prettyPrint(true);
String result = doc.outerHtml();
结果是:
<html>
<head>
</head>
<body>
<form method="post">
<select name="books"> <option value="111">111</option> <option value="222">222</option> </select>
</form>
</body>
</html>
<选项>元素都在同一条线上!
如何让Jsoup格式化< option>元素所以结果与输入相同,在这个例子中?
解决方法:
doc.outputSettings().charset("UTF-8");
从字符串解析html时,默认字符集为UTF-8,除非您使用File或InputStream作为解析输入设置字符集.
因此,OutputSettings上的charset默认与输入相同,在您的情况下为UTF-8.如果您希望它与输入不同,您只需要设置它.
Document.OutputSettings.charset()
Get the document’s current output charset, which is used to control which characters are escaped when generating HTML (via the html() methods), and which are kept intact.
Where possible (when parsing from a URL or File), the document’s output charset is automatically set to the input charset. Otherwise, it defaults to UTF-8.
doc.outputSettings().prettyPrint(true);
您不需要启用漂亮的打印,默认情况下它是打开的.
Document.OutputSettings.prettyPrint()
Get if pretty printing is enabled. Default is true. If disabled, the
HTML output methods will not re-format the output, and the output will
generally look like the input.
doc.outputSettings().outline(true);
这是关键标签.如果未设置,则仅显示块标签(选项为not a block tag).启用后,所有标记都被视为块元素.
Document.OutputSettings.outline()
Get if outline mode is enabled. Default is false. If enabled, the HTML output methods will consider all tags as block.
所以你的最后一段代码应该是这样的:
Document doc = Jsoup.parse(html);
doc.outputSettings().indentAmount(4).outline(true);
String result = doc.outerHtml();
产量
<html>
<head>
</head>
<body>
<form method="post">
<select name="books">
<option value="111">111</option>
<option value="222">222</option>
</select>
</form>
</body>
</html>
内容总结
以上是互联网集市为您收集整理的java – JSoup – 格式化元素全部内容,希望文章能够帮你解决java – JSoup – 格式化元素所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。