2

Currently I have a java application that loads XML from a local file into a string. My code looks like this

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

How can I get the contents of the XML file if it was located on the internet, at a URL like http://mydomain.com/xml/extract-2000.xml ?

jeph perro
  • 6,242
  • 26
  • 90
  • 124

2 Answers2

2

try the sax interface

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

For more information regarding SAX check this link

Semere Taézaz Sium
  • 4,036
  • 3
  • 21
  • 26
2

Check this code:

  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(); 
Kushan
  • 10,657
  • 4
  • 37
  • 41
  • +1 for Transformer. I would recommend using a StreamSource rather than a DOMSource to improve performance. – bdoughan Jan 16 '12 at 12:31