Parsing XML document YQL query in Java -
i want use information xml response produced using yql stock historical data, 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 stock objects array. new java , have no knowledge of xml api's. dont know simple way it. can suggest me solution. thanks.
you following using jaxb (jsr-222) implementation:
- metro jaxb (the reference implementation included in java se 6)
- eclipselink jaxb (moxy), i'm tech lead
- apache jaxme
- etc.
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; }
Comments
Post a Comment