package com.mypackage; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class SampleCode { /** * @param args */ public static void main(String[] args) { SampleCode test = new SampleCode(); Element ele = test.request("url"); } public Element request(String url) { Document doc = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setCoalescing(true); DocumentBuilder builder = factory.newDocumentBuilder(); URL reqURL = new URL(url); //将得到的Stream解析成xml文档类型 doc = builder.parse(reqURL.openStream(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } //假设xml中取得数据的根节点为"response" Element response = getElement(doc, "response"); return response; } public Element getElement(Document doc, String tagName) { NodeList ndList = doc.getElementsByTagName(tagName); if (ndList.getLength() == 1) { return (Element) ndList.item(0); } return null; } }