简体   繁体   English

从Java中的XML获取属性值

[英]Getting attributes values from XML in Java

I am trying to parse some data from the following site, to an Android App which I am creating 我正在尝试将以下站点中的一些数据解析到我正在创建的Android应用中

TFL Tube Data TFL管数据

The data in this feed is constantly updated and can hold anything from nothing to 15/16 items. 此Feed中的数据会不断更新,并且可以保存从零到15/16的所有内容。 The basic format of each item is as following: 每个项目的基本格式如下:

<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

I need to go through the entire and pull the value of the attribute of "Name" in Line and "Description" in "Status". 我需要遍历整个内容,并在“行”中提取“名称”的属性值,在“状态”中提取“描述”的属性值。 So in the above I would be pulling "Circle" and "Planned Closure". 因此,在上面,我将拉“ Circle”和“ Planned Closure”。 The classes I have made so far is as follows: 到目前为止,我进行的课程如下:

Main Class 主班

    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");
        }
    }
}

Handling XML 处理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);
            }

        }

Any Help on this would be greatly appreciated 任何帮助,将不胜感激

Thanks 谢谢

You're on the right track using the Attributes object, but you have to use the index position of the attribute within the element. 使用Attributes对象,您处在正确的轨道上,但必须使用属性在元素中的索引位置。

Hence you need to iterate through the attributes of the element using a for loop on the attributes.getName() method until attributes.getName(i).equals("Name"). 因此,您需要在attribute.getName()方法上使用for循环遍历元素的属性,直到attributes.getName(i).equals(“ Name”)。 Once you determine the index, just use attribute attributes.getValue(i). 确定索引后,只需使用属性attribute.getValue(i)。

It is hard to understand what you need, but you are getting the attributes wrong. 很难理解您需要什么,但是您弄错了属性。 I think it should somehow like this 我认为应该这样

else if (qName.equalsIgnoreCase("Status")) {
    object = new Status();
    object.id = attributes.getValue("ID");
    object.cssClass = attributes.getValue("CssClass");
    object.isActive = attributes.getValue("IsActive");
    object.description = attributes.getValue("Description");
}
else if (qName.equalsIgnoreCase("StatusType")) {
    object.typeId = attributes.getValue("ID");
    //etc, and maybe the StatusType should be a nested class of Status and stored in array field
}

And in your endElement 在你的endElement中

if (qName.equalsIgnoreCase("Status")) {
    statuses.add(object);
}

I'm too lazy to write the whole thing, I wrote it just to show how to get attributes. 我懒得写完整的东西,我写它只是为了展示如何获取属性。 Also, I prefer using android.sax instead of directly creating the DefaultHandler. 另外,我更喜欢使用android.sax而不是直接创建DefaultHandler。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM