public String transform_XML(String type, InputStream file){
TransformerFactory tf = TransformerFactory.newInstance();
String xslfile = "/StyleSheets/" + type + ".xsl";
Transformer t = tf.newTemplates(new StreamSource(this.getClass().getResourceAsStream(xslfile))).newTransformer();
Source source = new StreamSource(file);
CharArrayWriter wr = new CharArrayWriter();
StreamResult result = new StreamResult(wr);
t.transform(source, result);
return wr.toString();
}
上述方法将xsl和xml文件作为输入,并将转换后的结果作为String返回。来自包javax.xml.transform的类已用于实现此目的。
现在我可以使用相同的包来转换html文件吗? (由于包名称有xml,我非常怀疑它。)我该怎么做才能转换html文件?
答案 0 :(得分:1)
public class SimpleXSLT {
public static void main(String[] args) {
String inXML = "C:/tmp/temp.html";
String inXSL = "C:/tmp/temp.xsl";
String outTXT = "C:/tmp/temp_copy.html";
SimpleXSLT st = new SimpleXSLT();
try {
st.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
}
public void transform(String inXML,String inXSL,String outTXT)
throws TransformerConfigurationException,
TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(inXSL);
Transformer transformer = factory.newTransformer(xslStream);
transformer.setErrorListener(new MyErrorListener());
StreamSource in = new StreamSource(inXML);
StreamResult out = new StreamResult(outTXT);
transformer.transform(in,out);
System.out.println("The generated XML file is:" + outTXT);
}
}
答案 1 :(得分:1)
如您所知,html文档不是必需的有效xml。但是你可以将html转换为xml,之后使用有效的xml进行操作(转换后 - 你将得到DOM树)。
我建议您使用CyberNeko HTML Parser将html
转换为xml
。
草稿示例:
import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Document;
...
public Document parseHtml(InputStream is) throws Exception {
DOMParser parser = new DOMParser();
parser.parse(new InputSource(is));
return parser.getDocument();
}
如果您使用maven
- 只需从存储库http://mvnrepository.com/artifact/nekohtml/nekohtml添加到项目CyberNeko
答案 2 :(得分:1)