2011-05-08 237 views
2

我正在搜索可用於讀取XML文件的代碼。我確實找到了一個如下。但我的問題是,我無法在線閱讀XML文件。當我給出URL of the XML file位置時,它會返回「文件未找到異常」。可以有人建議。提前致謝。在線閱讀XML文件

import java.io.File; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 

public class XMLReader { 

public static void main(String argv[]) { 

    try { 
    File file = new File("MyXML.xml"); 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder db = dbf.newDocumentBuilder(); 
    Document doc = db.parse(file); 
    doc.getDocumentElement().normalize(); 
    System.out.println("Root element " + doc.getDocumentElement().getNodeName()); 
    NodeList nodeLst = doc.getElementsByTagName("employee"); 
    System.out.println("Information of all employees"); 

    for (int s = 0; s < nodeLst.getLength(); s++) { 

    Node fstNode = nodeLst.item(s); 

    if (fstNode.getNodeType() == Node.ELEMENT_NODE) { 

      Element fstElmnt = (Element) fstNode; 
     NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname"); 
     Element fstNmElmnt = (Element) fstNmElmntLst.item(0); 
     NodeList fstNm = fstNmElmnt.getChildNodes(); 
     System.out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue()); 
     NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname"); 
     Element lstNmElmnt = (Element) lstNmElmntLst.item(0); 
     NodeList lstNm = lstNmElmnt.getChildNodes(); 
     System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue()); 
    } 

    } 
    } catch (Exception e) { 
    e.printStackTrace(); 
    } 
} 
} 
+1

可能的重複[如何從Java中的URL讀取XML響應,](http://stackoverflow.com/questions/2310139/how-to-read-xml-response-from-a-url-in -java) – 2011-05-08 13:27:25

回答

1

您可以利用java.net.URL類:

URL xmlURL = new URL("http://www.cse.lk/listedcompanies/overview.htm?d-16544-e=3&6578706f7274=1"); 
InputStream xml = xmlURL.openStream(); 
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
Document doc = db.parse(xml); 
xml.close(); 
+0

非常感謝。有效 :) – 2011-05-08 16:24:52

0

如果你試圖用一個RESTful服務之間的通信,您可能會受益從使用庫。這個領域的開源軟件庫包括Apache CXF和Jersey。