java解析网络xml文档的方式有很多,本文提出一个比较简易的方法。代码如下:
public static Document getDocumentRemote(String path) {
try {
URL url = new URL(path);
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setValidating(false);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(url.openStream());
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("wrong file");
e.printStackTrace();
}
return null; }
try {
URL url = new URL(path);
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setValidating(false);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(url.openStream());
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("wrong file");
e.printStackTrace();
}
return null; }
最终返回的是一个Document对象,在org.w3c.dom包中,如包名所示,可以用w3c处理xml文档的方法来处理这个xml文件。