【发布时间】:2011-08-21 15:21:03
【问题描述】:
我们如何使用 Http 类 api 将 html 转换为格式良好的 xhtml,如果可能,请提供 演示代码....谢谢
【问题讨论】:
-
什么是“Http 类 api”?
-
@skaffman 可能是
java.net之类的。
标签: java
我们如何使用 Http 类 api 将 html 转换为格式良好的 xhtml,如果可能,请提供 演示代码....谢谢
【问题讨论】:
java.net 之类的。
标签: java
可以使用以下方法从html中获取xhtml
public static String getXHTMLFromHTML(String inputFile,
String outputFile) throws Exception {
File file = new File(inputFile);
FileOutputStream fos = null;
InputStream is = null;
try {
fos = new FileOutputStream(outputFile);
is = new FileInputStream(file);
Tidy tidy = new Tidy();
tidy.setXHTML(true);
tidy.parse(is, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
if(fos != null){
try {
fos.close();
} catch (IOException e) {
fos = null;
}
fos = null;
}
if(is != null){
try {
is.close();
} catch (IOException e) {
is = null;
}
is = null;
}
}
return outputFile;
}
【讨论】:
outputFile 声明为参数,则不必另外声明return。 Java 的参数传递是按值传递的,对于引用类型,如String,此值是对调用者创建和传递的对象(在堆上)的引用。这意味着,一旦函数结束,调用者也可以看到函数内部对其进行的更改。 (除了在存在为我们这样做的库时再次发明这个轮子;请参阅其他答案。)
我只是使用 Jsoup 完成的,如果它适合你的话:
private String htmlToXhtml(final String html) {
final Document document = Jsoup.parse(html);
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
return document.html();
}
我的解决方案来自一些有用的内容:
【讨论】:
看看 J-Tidy:http://jtidy.sourceforge.net/ 它通常可以很好地清理杂乱的 html 并将其转换为 xhtml。
【讨论】: