我嘗試使用STAX從URI解析XML文件!stax從元素獲得屬性值
XML看起來像這樣:
<Type type_id="4218">
<Title>English Premier League</Title>
<Event start_time="2011-12-18 16:10:00" ev_id="2893772">
<Description>Manchester City v Arsenal</Description>
<Market mkt_typ="Win/Draw/Win">
<Occurrence bet_id="42455761" decimal="1.6666666666667">
<Description>Manchester City</Description>
</Occurrence>
<Occurrence bet_id="42455762" decimal="3.6">
<Description>Draw</Description>
</Occurrence>
<Occurrence bet_id="42455764" decimal="5">
<Description>Arsenal</Description>
</Occurrence>
</Market>
</Event>
</Type>
輸出應該是:
id:4218
title:English Premier League
ev_id:2893772
date of match:Sun Dec 18 16:10:00 CET 2011
description:Manchester City v Arsenal
one:1.6666666666667
draw:3.6
two:5
我的代碼看起來是這樣的:
XMLInputFactory factory = XMLInputFactory.newInstance();
try {
XMLStreamReader streamReader = factory.createXMLStreamReader(new URL("http://cubs.bluesq.com/cubs/cubs.php?action=getpage&thepage=385.xml").openStream());
while (streamReader.hasNext()) {
int event = streamReader.next();
if(event == XMLStreamConstants.START_ELEMENT){
if(streamReader.getLocalName().equals("Type")){
long id = Integer.parseInt(streamReader.getAttributeValue(null, "type_id"));
if(id == 4218){
System.out.println("id:"+id);
streamReader.nextTag();
System.out.println("title:"+streamReader.getElementText());
streamReader.nextTag();
int ev_id = Integer.parseInt(streamReader.getAttributeValue(null, "ev_id"));
System.out.println("ev_id:"+ev_id);
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
formater.setTimeZone(TimeZone.getTimeZone("CET"));
String tempDatum = streamReader.getAttributeValue(null,"start_time");
Date dateOfMatch = formater.parse(tempDatum);
System.out.println("date of match:"+dateOfMatch);
streamReader.nextTag();
String description = streamReader.getElementText();
System.out.println("description:"+ description);
streamReader.nextTag();
String market = streamReader.getAttributeValue(null, "mkt_typ");
if(market.equals("Win/Draw/Win")){
streamReader.nextTag();
double one = Double.parseDouble(streamReader.getAttributeValue(null, "decimal"));
System.out.println("one:"+ one);
double draw = Double.parseDouble(streamReader.getAttributeValue(null, "decimal"));
System.out.println("draw:"+draw);
double two = Double.parseDouble(streamReader.getAttributeValue(null, "decimal"));
System.out.println("two:"+two);
}
}
}
}
}
此代碼產生輸出:
id:4218
title:English Premier League
ev_id:2893772
date of match:Sun Dec 18 16:10:00 CET 2011
description:Manchester City v Arsenal
one:1.6666666666667
draw:1.6666666666667
two:1.6666666666667
如何從元素「Occurrence」中的屬性「decimal」中獲取其他值?
這看起來像XSLT和/或XPath工作......我確定你有使用這個庫的理由,但我不知道它是否有用,但我確實知道XPath和XSLT非常棒,它們(特別是XPath)可以很容易地輸出結果(恕我直言) – 2011-12-14 18:55:25