目前我有一个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这样的网址,我如何获取该文件的内容?
答案 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();