【问题标题】:Reading XML file online在线读取 XML 文件
【发布时间】:2011-08-21 02:58:45
【问题描述】:

我正在搜索可用于读取 XML 文件的代码。我确实找到了一个如下。但我的问题是,我无法在线读取 XML 文件。当我给出URL of the XML file 位置时,它返回文件未找到异常。有人可以建议。提前致谢。

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();
  }
 }
}

【问题讨论】:

标签: java xml parsing file uri


【解决方案1】:

在 stackoverflow 上讨论过:How to read XML response from a URL in java?

【讨论】:

    【解决方案2】:

    您可以利用 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();
    

    【讨论】:

      【解决方案3】:

      如果您尝试与 Restful 服务进行通信,您可能会从使用库中受益。在这方面具有优势的开源库包括 Apache CXF 和 Jersey。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-22
        • 1970-01-01
        • 2014-01-28
        • 2019-11-19
        • 1970-01-01
        • 2013-04-09
        相关资源
        最近更新 更多