1. org.w3c.dom.Document对象转成org.jsoup.nodes.Document对象:
- String fragment = "<data><employee><name id=\"1\">益达</name><name id=\"2\">yida</name>"
- + "<title>Manager</title></employee></data>";
- XMLUtils util = new XMLUtils();
- //先得到W3C Document对象
- Document doc = util.fragment2Document(fragment);
- //将W3C Document对象转成XML字符串
- DOMSource domSource = new DOMSource(doc);
- StringWriter writer = new StringWriter();
- StreamResult result = new StreamResult(writer);
- TransformerFactory tf = TransformerFactory.newInstance();
- Transformer transformer = tf.newTransformer();
- transformer.transform(domSource, result);
- System.out.println(writer.toString());
然后XML String to jsoup Document对象,so easy!
- //这里xmlString表示xml字符串代码片段
- org.jsoup.nodes.Document document = org.jsoup.Jsoup.parse(xmlString);
2.org.jsoup.nodes.Document对象转成org.w3c.dom.Document对象:
- org.jsoup.helper.W3CDom w3cDom = new W3CDom();
- //这里的doc对象指的是jsoup里的Document对象
- org.w3c.dom.Document w3cDoc = w3cDom.fromJsoup(doc);
注意:org.jsoup.helper.W3CDom类在jsoup-1.7.x.jar里是不存在的,请使用jsoup-1.8.3.jar,特此提醒!谢谢!
转载:http://iamyida.iteye.com/blog/2247570