Java - read XML from a URL

Asked

Viewed 361 times

0

I have a function that reads XML and it works 100%, the problem is that when I try to read an XML that is online on my server I cannot.

Follows code:

public int lerXml() throws JDOMException, IOException, URISyntaxException {
    URL url = new URL("http://br728.teste.website/~ayzac296/smh/xml.xml");
    File f = new File(url.toURI());
    SAXBuilder sb = new SAXBuilder();
    Document d;
    try {
        d = sb.build(f);
    } catch (Exception e) {
        System.out.println(e);
        return 0;
    }
    Element mural = d.getRootElement();
    List elements = mural.getChildren();
    Iterator i = elements.iterator();
    while (i.hasNext()) {
        Element element = (Element) i.next();
        if (Double.parseDouble(element.getChildText("tempo")) >= mediaPlayer.getCurrentTime().toSeconds()) {
            //System.out.println("Nome:" + element.getChildText("nome"));
            //System.out.println("Tempo:" + element.getChildText("tempo"));
            System.out.println("Menssagem:" + element.getChildText("conteudo"));
        }
    }

    return 1;
}

It is showing the following error:

Exception in thread "Thread-179" java.lang.Illegalargumentexception: URI Scheme is not "file"

I’m having trouble turning the URL into File.

Thank you.

  • You need an http connection to download things from http. I’ll give you an answer explaining this already

1 answer

1


You can simply pass your URL to Saxbuilder. Thus:

d = sb.build(url);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.