如何将XML文件从Internet加载到字符串中

时间:2012-01-16 06:06:44

标签: java xml string sax gnu-fileutils

目前我有一个java应用程序,它将XML从本地文件加载到字符串中。我的代码看起来像这样

     private String xmlFile = "D:\\mylocalcomputer\\extract-2339393.xml";
     String fileStr = FileUtils.readFileToString(new File(xmlFile));

如果XML文件位于互联网上,如http://mydomain.com/xml/extract-2000.xml这样的网址,我如何获取该文件的内容?

2 个答案:

答案 0 :(得分:2)

尝试sax接口

private String xmlURL = "http://mydomain.com/xml/extract-2000.xml";

XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(handler);
reader.parse(new InputSource(new URL(xmlURL).openStream()));

有关SAX检查this link

的更多信息

答案 1 :(得分:2)

检查此代码:

  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  InputStream inputStream = new FileInputStream(new File("http://mydomain.com/xml/extract-2000.xml"));
  org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
  StringWriter stw = new StringWriter();
  Transformer serializer = TransformerFactory.newInstance().newTransformer();
  serializer.transform(new DOMSource(doc), new StreamResult(stw));
  stw.toString();