0

I'm using an existing XMLReader code in my project for taking elements from an XML page. It works fine for only one element like this:

    public String getURL(String Url) {

    BufferedReader br = null;

    try {

        URL url = new URL(Url);
        br = new BufferedReader(new InputStreamReader(url.openStream()));

        String line;

        StringBuilder sb= new StringBuilder();

        while ((line = br.readLine()) != null) {
            if(line.contains("presentationURL")) {
                line = line.split("<presentationURL>")[1].split("</presentationURL>")[0];
            sb.append(line);
            sb.append(System.lineSeparator());
            }
        }
        return sb.toString();

... But when I try to add a second element right after here:

if(line.contains("presentationURL")) {
line = line.split("<presentationURL>")[1].split("</presentationURL>")[0];
sb.append(line);
sb.append(System.lineSeparator());
}

like this:

if(line.contains("manufacturer")) {
line = line.split("<manufacturer>")[1].split("manufacturer")[0];
sb.append(line);
sb.append(System.lineSeparator());
}

the program gives me Array Index Out of Bounds Exception and some other errors. How can I make this program work for more elemets?

  • 2
    Do *not* to use `String.split` or other low-level string operations to read XML, because it leads to restrictions and errors (as you now already noticed). Instead, use an [XML parser](https://stackoverflow.com/questions/1722140/how-can-i-parse-xml-using-java). – Thomas Fritsch Sep 06 '18 at 08:56
  • Do you need collect all tags or any of you know? You can see, how do it with XMLStreamReader https://stackoverflow.com/questions/51836506/how-to-get-prensentationurl-from-xml-page-with-java/51858738#51858738 – Steklorez Sep 06 '18 at 09:11
  • Can I use XML parser for urls? @ThomasFritsch – firestarter Sep 06 '18 at 10:07
  • @firestarter yes, i think so. As far as i remember you can read XML from URL, InputStream, File, Reader, ... – Thomas Fritsch Sep 06 '18 at 10:57
  • Agreed with @ThomasFritsch , Use stax pai to read xml from an inputstream . https://stackoverflow.com/questions/4652299/read-xml-string-using-stax – user595226 Sep 06 '18 at 11:58

0 Answers0