Reputation:
Hi I am working with Document Class. When I am reading File from local system it is working and when I want to read the file and try to load the XML Document from some URL its not working.
private static Document loadTestDocument(String fileLocation) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder db = factory.newDocumentBuilder();
File file = new File(fileLocation);
System.out.println(db.parse(file).toString());
return db.parse(file);
}
So this method is returning Document if I have a service which returns xml and I want to consume it how can I do this I want to directly load from the service GET url.
I tried with this but its not working
File file = new File("http://someservice/getdata");
Error: File not found Then I tried to load it from Input Stream it also not working from me.
InputStream input = new URL("http://someurl:32643/api/values").openStream();
Error:
[Fatal Error] :1:1: Content is not allowed in prolog.
Now how can I achieve this any help will be appreciated I want to load the data received from the service and want to return a Document of that as I am returning in my method.
Upvotes: 0
Views: 16846
Reputation: 6230
The following code works for me.
TestXML.java
import java.net.URL;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class TestXML {
private static Document loadTestDocument(String url) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory.newDocumentBuilder().parse(new URL(url).openStream());
}
public static void main(String[] args) throws Exception {
Document doc = loadTestDocument("http://www.enetpulse.com/wp-content/uploads/sample_xml_feed_enetpulse_soccer.xml");
System.out.println(doc);
doc = loadTestDocument("http://localhost/array.xml");
System.out.println(doc);
}
}
array.xml
<?xml version="1.0"?>
<ArrayOfstring xmlns:i="w3.org/2001/XMLSchema-instance" xmlns="schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>
Do you actually need/use the xmlns attributes though?
Upvotes: 2