下面是使用Dom4j的代码,你的Document也不知道是哪个包里的 One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.import java.net.URL;import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader;public class Foo { public Document parse(URL url) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(url); return document; } }
额。用的是w3c包里的 另外问下url的用法。这个不是指定xml文件路径的地址码?
new URI(path).toURL()就可以了
报错呢: Exception in thread "main" java.lang.IllegalArgumentException: URI is not absolute at java.net.URI.toURL(URI.java:1080) at com.dong.sendxml.TestMain.main(TestMain.java:19) 我的代码:URL xmlurl = new URI("holiday.xml").toURL(); try { Document doc = tm.parse(xmlurl); System.out.println("ooxx:" +doc); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); }
给LZ一个转W3C Document的代码public static Document parse(String s) { InputStream is = new java.io.ByteArrayInputStream(xmlString.getBytes()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.import java.net.URL;import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;public class Foo { public Document parse(URL url) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(url);
return document;
}
}
另外问下url的用法。这个不是指定xml文件路径的地址码?
Exception in thread "main" java.lang.IllegalArgumentException: URI is not absolute
at java.net.URI.toURL(URI.java:1080)
at com.dong.sendxml.TestMain.main(TestMain.java:19)
我的代码:URL xmlurl = new URI("holiday.xml").toURL();
try {
Document doc = tm.parse(xmlurl);
System.out.println("ooxx:" +doc);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream is = new java.io.ByteArrayInputStream(xmlString.getBytes());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(is);
} catch (SAXParseException spe) {
} catch (SAXException sxe) {
} catch (ParserConfigurationException pce) {
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
}
return null;
}
如果不是String是文件的话:Document doc = parse(new FileInputStream(file))