Pick up a XML list in JAVA

Asked

Viewed 370 times

2

I’m trying to get an XML list but I can’t put it in the variable.

Main class:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

public class Teste {

  private final String USER_AGENT = "Mozilla/5.0";

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

    Teste http = new Teste();

    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://www.teste.com/cars.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()));

    try {

      String message = org.apache.commons.io.IOUtils.toString(in);

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



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

    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

  }
}

Cars class:

import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement (name = "Cars")

public class Cars {
  private ArrayList<Car> cars = new ArrayList<>();

  public ArrayList<Car> getCars() {
    return cars;
  }

  @XmlElement
  public void setCars(ArrayList<Car> cars) {
    this.cars = cars;
  }

}

Car class:

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 + '}';
  }
}

And XML:

<Cars>
<Car>
<manufacturerCar>VW</manufacturerCar>
<modelCar>FUSCA</modelCar>
<doorsCar>2</doorsCar>
<gearshift>MANUAL</gearshift>
</Car>
<Car>
<manufacturerCar>FORD</manufacturerCar>
<modelCar>FOCUS</modelCar>
<doorsCar>4</doorsCar>
<gearshift>AUTOMATICO</gearshift>
</Car>
<Car>
<manufacturerCar>FIAT</manufacturerCar>
<modelCar>UNO</modelCar>
<doorsCar>4</doorsCar>
<gearshift>MANUAL</gearshift>
</Car>
<Car>
<manufacturerCar>VW</manufacturerCar>
<modelCar>UP!</modelCar>
<doorsCar>4</doorsCar>
<gearshift>AUTOMATICO</gearshift>
</Car>
<Car>
<manufacturerCar>PORSHE</manufacturerCar>
<modelCar>Q100</modelCar>
<doorsCar>2</doorsCar>
<gearshift>AUTOMATICO</gearshift>
</Car>
<Car>
<manufacturerCar>RENAULT</manufacturerCar>
<modelCar>DUSTER</modelCar>
<doorsCar>4</doorsCar>
<gearshift>Manual</gearshift>
</Car>
<Car>
<manufacturerCar>HONDA</manufacturerCar>
<modelCar>CIVIC</modelCar>
<doorsCar>4</doorsCar>
<gearshift>Manual</gearshift>
</Car>
<Car>
<manufacturerCar>MITSUBISHI</manufacturerCar>
<modelCar>PAJERO</modelCar>
<doorsCar>4</doorsCar>
<gearshift>Manual</gearshift>
</Car>
</Cars>

The variable cars ends up returning "Null".

1 answer

0


You are "consuming" the stream on the line String message = org.apache.commons.io.IOUtils.toString(in);.

When trying to make unmarshal Cars cars = (Cars) cu.unmarshal(in); The stream read position is at the end of it, so no byte is returned.

You can comment on the String message = org.apache.commons.io.IOUtils.toString(in); or use String message in unmarshal Cars class.

To solve the parse problem in the list include the element name in the Cars entity:

import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement (name = "Cars")

public class Cars {
    private ArrayList<Car> cars = new ArrayList<>();

    public ArrayList<Car> getCars() {
        return cars;
    }
    //Incluido o nome do elemento
    @XmlElement(name="Car")
    public void setCars(ArrayList<Car> cars) {
        this.cars = cars;
    }

}
  • I did what you said, now it creates the Cars object, however the list returns empty. Can you explain this "consuming", I would be literally sending the stream to the message and leaving the stream empty?

  • Exact. Imagine that Stream is an array of bytes with a pointer pointing to the next input that should be read. When reading Inputstream with org.apache.commons.io.IOUtils.toString(in) the pointer reaches the last input of the array. So when you try to read srteam again with cu.unmarshal(in); it returns nothing because the pointer is already at the end.

  • Thanks for the great explanation, @fhofmann !

Browser other questions tagged

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