-1
我需要編寫一個簡單的函數來解析xml從Java的URL與DOM。 這是xml url。如何從URL讀取XML響應?
如果我把它寫入/assets/exampleXML.xml並使用這段代碼都可以。
static final String NODE_EMP = "Record";
static final String NODE_NAME = "Nominal";
static final String NODE_SALARY = "Value";
.....
public void onBtnClick3(View v) {
XMLDOMParser parser = new XMLDOMParser();
try {
InputStream is = getAssets().open("exampleXML2.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
NodeList nodeList = doc.getElementsByTagName(NODE_EMP);
for (int i = 0; i < nodeList.getLength(); i++) {
Element e = (Element) nodeList.item(i);
nameText.append(parser.getValue(e, NODE_NAME) + "\n");
nameText.append(parser.getValue(e, NODE_SALARY) + "\n");
}
但是,如果我改變
public static final String QUERY_URL = "http://www.cbr.ru/scripts/XML_dynamic.asp?......";
public void onBtnClick(View v) {
XMLDOMParser parser = new XMLDOMParser();
try {
URL url = new URL(QUERY_URL);
URLConnection conn = url.openConnection();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(conn.getInputStream());
這是行不通的。什麼是問題以及如何解決它? 我已閱讀它,但它不起作用。請幫幫我。 How to read XML response from a URL in java?