Difficulty reading XML in Java

Asked

Viewed 231 times

0

I’m trying to learn, and I’m having a hard time reading an XML by taking it via the Web and turning it into an object. There is a ready code in which it connects to the site, and another that a friend showed me that I should pass the XML to an object but that does not happen. Can you tell me errors in this code? I can’t find clear examples of how to access a website and get information.

Main Class:

com.mkyong;

import com.sun.jmx.remote.internal.Unmarshal;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

public class HttpURLConnectionExample {

  private final String USER_AGENT = "Mozilla/5.0";

  public static void main(String[] args) throws Exception {

    HttpURLConnectionExample http = new HttpURLConnectionExample();

    System.out.println("Testing 1 - Send Http GET request");
    http.sendGet();

//      System.out.println("\nTesting 2 - Send Http POST request");
//      http.sendPost();
  }

  // HTTP GET request
  private void sendGet() throws Exception {

    String url = "http://teste.com/car.xml";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    try {

      //Transforma xml em objeto
      JAXBContext aXBContext = JAXBContext.newInstance(Car.class);
      Unmarshaller cu = aXBContext.createUnmarshaller();
      Car car = (Car) cu.unmarshal(in);


      if(car != null){
        System.out.println("Não é nulo!");
      }

    } catch (Exception e) {
    }

    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

  }

Car class:

package com.mkyong;

public class Car {

  private String manufacturerCar;
  private String modelCar;
  private String doorsCar;
  private String gearshift;  

  public String getManufacturerCar() {
    return manufacturerCar;
  }

  public void setManufacturerCar(String manufacturerCar) {
    this.manufacturerCar = manufacturerCar;
  }

  public String getModelCar() {
    return modelCar;
  }

  public void setModelCar(String modelCar) {
    this.modelCar = modelCar;
  }

  public String getDoorsCar() {
    return doorsCar;
  }

  public void setDoorsCar(String doorsCar) {
    this.doorsCar = doorsCar;
  }

  public String getGearshift() {
    return gearshift;
  }

  public void setGearshift(String gearshift) {
    this.gearshift = gearshift;
  }

  @Override
  public String toString() {
    return "Car{" + "manufacturerCar=" + manufacturerCar + ", modelCar=" + modelCar + ", doorsCar=" + doorsCar + ", gearshift=" + gearshift + '}';
  }


}

Follows the XML

<Car>
  <manufacturerCar>VW</manufacturerCar>
  <modelCar>Fusca</modelCar>
  <doorsCar>2</doorsCar>
  <gearshift>Manual</gearshift>
</Car>

Well, thanks in advance!

  • Where is your class Car?

  • @Sorack will edit and put it. Ready!

  • To String of XML that you receive from the service is exactly the same as the one that you placed?

  • @Sorack Yes, however this String in which I receive all XML information is part of a code I took to test in which it just shows you the answer and puts the whole scope of the site in a string.

2 answers

2

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        Document doc;
        try {
            builder = factory.newDocumentBuilder();
            doc =  builder.parse(new InputSource( new StringReader(inputLine)));
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            ex.printStackTrace();
        }

Barter:

  Car car = (Car) cu.unmarshal(in);

For:

  Car car = (Car) cu.unmarshal(doc);
  • It gives incompatible types error: Bufferedreader / String

  • new Stringreader(inputLine))

  • I’ll try and edit here!

1


You have to add class annotations Car:

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Car")
public class Car {

  private String manufacturerCar;
  private String modelCar;
  private String doorsCar;
  private String gearshift;

  public String getManufacturerCar() {
    return manufacturerCar;
  }

  @XmlElement
  public void setManufacturerCar(String manufacturerCar) {
    this.manufacturerCar = manufacturerCar;
  }

  public String getModelCar() {
    return modelCar;
  }

  @XmlElement
  public void setModelCar(String modelCar) {
    this.modelCar = modelCar;
  }

  public String getDoorsCar() {
    return doorsCar;
  }

  @XmlElement
  public void setDoorsCar(String doorsCar) {
    this.doorsCar = doorsCar;
  }

  public String getGearshift() {
    return gearshift;
  }

  @XmlElement
  public void setGearshift(String gearshift) {
    this.gearshift = gearshift;
  }

  @Override
  public String toString() {
    return "Car{" + "manufacturerCar=" + manufacturerCar + ", modelCar=" + modelCar + ", doorsCar=" + doorsCar + ", gearshift=" + gearshift + '}';
  }
}
  • Perfectly uploaded the XML information, thank you very much! Not to abuse your patience: could I do this with local file the same way? And would the Car class still be able to be used as a class or is it just used to load XML? I need to learn POST/GET methods besides XML, would you indicate any location for it? Well, thank you very much!

  • 1

    Could, you can use any kind of InputStream. The class Car remains the same. As for the methods REST It ends up being something very extensive, has a lot of material over the Internet. Don’t forget to accept the answer so that people with similar doubt benefit too

  • It is returning an error from java.io.Ioexception, however loads the XML, know what might be causing this in this file?

  • @G.Falcão there is file reading problem. You have to create a specific question for this

Browser other questions tagged

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