Difficulty in reading XML in Java

0

I'm trying to learn, and I'm having a hard time reading an XML catching via WEB and turning it into an object. There is a ready code in which it makes the connection to the site, and another that a friend has shown me that I should pass the XML to an object however this does not occur. Can you point me to bugs in this code? I do not 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 + '}';
  }


}

Follow the XML

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

Well, thank you in advance!

    
asked by anonymous 28.09.2017 / 20:17

2 answers

1

You have to add the annotations of class 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 + '}';
  }
}
    
28.09.2017 / 21:19
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();
        }

Exchange:

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

By:

  Car car = (Car) cu.unmarshal(doc);
    
28.09.2017 / 21:09