任何人都可以建议我使用java将html转换为xml的最佳方法 有没有可用的API? html也可能包含javascript代码
我试过下面的代码:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import java.io.IOException;
class HTML2XML {
public static void main(String args[]) throws JDOMException {
InputStream isInHtml = null;
URL url = null;
URLConnection connection = null;
DataInputStream disInHtml = null;
FileOutputStream fosOutHtml = null;
FileWriter fwOutXml = null;
FileReader frInHtml = null;
BufferedWriter bwOutXml = null;
BufferedReader brInHtml = null;
try {
// url = new URL("www.climb.co.jp");
// connection = url.openConnection();
// isInHtml = connection.getInputStream();
frInHtml = new FileReader("D:\\Second.html");
brInHtml = new BufferedReader(frInHtml);
SAXBuilder saxBuilder = new SAXBuilder(
"org.ccil.cowan.tagsoup.Parser", false);
org.jdom.Document jdomDocument = saxBuilder.build(brInHtml);
XMLOutputter outputter = new XMLOutputter();
org.jdom.output.Format newFormat = outputter.getFormat();
String encoding = "iso-8859-2";
newFormat.setEncoding(encoding);
outputter.setFormat(newFormat);
try {
outputter.output(jdomDocument, System.out);
fwOutXml = new FileWriter("D:\\Second.xml");
bwOutXml = new BufferedWriter(fwOutXml);
outputter.output(jdomDocument, bwOutXml);
System.out.flush();
} catch (IOException e) {
}
} catch (IOException e) {
} finally {
System.out.flush();
try {
isInHtml.close();
disInHtml.close();
fosOutHtml.flush();
fosOutHtml.getFD().sync();
fosOutHtml.close();
fwOutXml.flush();
fwOutXml.close();
bwOutXml.close();
} catch (Exception w) {
}
}
}
}
但它没有按预期工作
答案 0 :(得分:1)
尝试jTidy
JTidy可以用作清理格式错误和错误的HTML的工具
答案 1 :(得分:1)
如果要解析html而不是将html转换为xml,可以使用html解析器。 http://www.mkyong.com/java/jsoup-html-parser-hello-world-examples/ http://htmlparser.sourceforge.net/javadoc/doc-files/using.html 我希望它可以帮助你。
答案 2 :(得分:0)
HTML与XML不同,除非它在XML模式下符合XHTML或HTML5。
建议使用HTML解析器读取HTML并将其转换为XML - 或直接处理它。