Prazanna
Prazanna

Reputation: 43

Parsing XML document YQL query in Java

I want to use the information from XML response produced by using YQL for stock historical data, like this link

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20in%20(%22MSFT%22)%20and%20startDate%3D%222011-2-12%22%20and%20endDate%3D%222011-2-15%22%0A%09%09&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env

And store it into a stock objects array. I am new to Java and I have no knowledge of its XML api's. I dont know what is the simple way to do it. Can someone suggest me a good solution. Thanks.

Upvotes: 1

Views: 3835

Answers (1)

bdoughan
bdoughan

Reputation: 148977

You could do the following using a JAXB (JSR-222) implementation:

Demo

import java.io.InputStream;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Stock.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        URL url = new URL("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20in%20(%22MSFT%22)%20and%20startDate%3D%222011-2-12%22%20and%20endDate%3D%222011-2-15%22%0A%09%09&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env");
        InputStream xmlStream = url.openStream();
        Stock stock = (Stock) unmarshaller.unmarshal(xmlStream);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(stock, System.out);
    }

}

Stock

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="query")
@XmlAccessorType(XmlAccessType.FIELD)
public class Stock {

    @XmlElementWrapper(name="results")
    @XmlElement(name="quote")
    private List<Quote> quotes;

}

Quote

import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;

@XmlAccessorType(XmlAccessType.FIELD)
public class Quote {

    @XmlElement(name="Date")
    @XmlSchemaType(name="date")
    private Date date;

    @XmlElement(name="Open")
    private double open;

    @XmlElement(name="High")
    private double high;

    @XmlElement(name="Low")
    private double low;

    @XmlElement(name="Close")
    private double close;

    @XmlElement(name="Volume")
    private long volume;

    @XmlElement(name="Adj_Close")
    private double adjClose;

}

Upvotes: 4

Related Questions