我正在尝试将以下站点中的一些数据解析到我正在创建的 Android 应用程序
此提要中的数据不断更新,可以包含从无到 15/16 项的任何内容。每个项目的基本格式如下:
<ArrayOfLineStatus> - BEGINNING OF XML DOCUMENT
<LineStatus ID="10" StatusDetails="No service this weekend due to planned engineering work.">
<BranchDisruptions/>
<Line ID="7" Name="Circle"/>
<Status ID="CS" CssClass="DisruptedService" Description="Planned Closure" IsActive="true">
<StatusType ID="1" Description="Line"/>
</Status>
</LineStatus>
<ArrayOfLineStatus> - END OF XML DOCUMENT
我需要遍历整个并提取 Line 中的“Name”属性和“Status”中的“Description”属性的值。所以在上面我会拉“圈子”和“计划关闭”。到目前为止,我所做的课程如下:
主班
public class TubeStatusXMLParsing extends Activity {
static final String baseURL = "http://cloud.tfl.gov.uk/TrackerNet
/LineStatus/IncidentsOnly";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(icicle);
setContentView(R.layout.tube_status);
getStatus();
}
public void getStatus() {
// TODO Auto-generated method stub
try{
URL website = new URL(baseURL);
//getting xmlreader to parse data
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(website.openStream()));
String listofStatuses = doingWork.getInformation();
circleStatus.setText(listofStatuses);
}catch (Exception e){
circleStatus.setText("error");
}
}
}
处理 XML
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.sax.Element;
import android.sax.RootElement;
public class HandlingXMLStuff extends DefaultHandler {
private ArrayList<String>statuses = null;
String status;
String lineName;
public String getInformation(){
return statuses.get(0);
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(qName.equalsIgnoreCase("ArrayOfLineStatus")){
statuses = new ArrayList<String>();
}else if(qName.equalsIgnoreCase("Status")){
status = attributes.getValue("Status");
statuses.add(status);
}
}
对此的任何帮助将不胜感激
谢谢