简体   繁体   English

如何从SD卡读取XML文件?

[英]How can I read an XML file from an SD card?

I want to parse an XML file from an SD card on Android, and I have to show the result in list view format. 我想从Android上的SD卡解析XML文件,并且必须以列表视图格式显示结果。 I tried to do it with this code: 我尝试使用以下代码进行操作:

for (int i = 0; i < obj_nod_list.getLength(); i++) {
    Node list = obj_nod_list.item(i); String strText =
        list.getFirstChild().getNodeValue();

but it results in a org.apache.harmony.xml.dom.ElementImpl exception. 但是会导致org.apache.harmony.xml.dom.ElementImpl异常。 What am I doing wrong? 我究竟做错了什么?

Here is my XML Parser: 这是我的XML分析器:

public class XMLReaderMarca extends DefaultHandler {
private static String TAG = "TAG";

/** Buffer que guarda as informações quando um texto é encontrado */
private StringBuffer valorAtual = new StringBuffer();

/** Lista que possui os objetos do arquivo XML */
private ArrayList<Marca> lista = new ArrayList<Marca>();

// private ArrayList<Produto> lista;

public ArrayList<Marca> getLista() {
    return lista;
}

/** apenas para coletar as informações do XML */
private Marca objetoTemp;

/**
 * Constutor que inicializa os objetos necessários para fazer o parse do
 * arquivo xml
 */
public void parse(String _caminho) {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser parser = spf.newSAXParser();

        File file = new File(_caminho);

        Log.i(TAG, " -- Inicio do XMLReaderMarca.parse --");
        parser.parse(file, this);
        Log.i(TAG, " -- Fim do XMLReaderMarca.parse --");

        file.delete();

    } catch (ParserConfigurationException e) {
        Log.i(TAG,
                "XMLReaderMarca.parse: O parser não foi configurado corretamente.");
    } catch (SAXException e) {
        Log.i(TAG,
                "XMLReaderMarca.parse: Problema ao fazer o parse do arquivo.");
    } catch (IOException e) {
        Log.i(TAG, "XMLReaderMarca.parse: O arquivo não pode ser lido.");
    }
}

/**
 * Indica que o parser achou o início do documento XML. Este evento não lhe
 * passa qualquer informação, apenas indica que o parser vai começar a
 * escanear o arquivo XML.
 */
public void startDocument() {
    Log.i(TAG, "Iniciando a leitura do XML em XMLReaderMarca");
}

/**
 * Indica que o parser achou e fim do documento XML.
 */
public void endDocument() {
    Log.i(TAG, "Finalizou a leitura do XML em XMLReaderMarca");
}

/**
 * Indica que o parser achou o início de uma tag (tag de abertura/início).
 * Este evento fornece o nome do elemento, o nome e valor dos atributos
 * deste elemento, e também pode fornecer as informações sobre o namespace.
 */
public void startElement(String uri, String localName, String tag,
        Attributes atributos) {

    valorAtual.setLength(0);

    if (tag.equalsIgnoreCase("Marca")) {
        objetoTemp = new Marca();
    }
    /*
     * //se o elemento possui atributos, imprime for (int i=0; i<
     * atributos.getLength(); i++){ if
     * (atributos.getQName(i).equalsIgnoreCase(ATT_ID)){
     * contatoTemp.setId(Integer.parseInt(atributos.getValue(i))); } else if
     * (atributos.getQName(i).equalsIgnoreCase(ATT_GRAVADO)){
     * contatoTemp.setGravado(atributos.getValue(i)); } }
     */
}

/**
 * Indica que o parser achou o fim de uma tag/elemento. Este evento fornece
 * o nome do elemento, e também pode fornecer as informações sobre o
 * namespace.
 */
public void endElement(String uri, String localName, String tag) {

    // adiciona o objeto na lista
    if (tag.equalsIgnoreCase("Marca")) {
        lista.add(objetoTemp);
    }
    // senão, seta os atributos
    else if (tag.equalsIgnoreCase(Marca.TAGS[0])) {
        objetoTemp.setCd_marca(validaStringInteger(valorAtual.toString()));
    } else if (tag.equalsIgnoreCase(Marca.TAGS[1])) {
        objetoTemp.setDs_marca(valorAtual.toString());
    }

    // limpa o valor Atual
    valorAtual.delete(0, valorAtual.length());
}

/**
 * Indica que o parser achou algum Texto (Informação).
 */
public void characters(char[] ch, int start, int length) {
    valorAtual.append(ch, start, length);
}

private Integer validaStringInteger(String string) {
    return isDigit(string) ? Integer.valueOf(string) : 0;
}

private Double validaStringDouble(String string) {
    return Double.valueOf(string);
}

boolean isDigit(String s) {
    return s.matches("[0-9]*");
}
}

My "TAGs" are the field's name, with this you don't need any external libs. 我的“ TAG”是该字段的名称,有了它,您不需要任何外部库。

Sorry, but the code's comments is in Portuguese (Brazil), I can't translate right now, sorry :( 抱歉,但是代码的注释是葡萄牙语(巴西),我现在无法翻译,抱歉:(

[]'s Bertan []的Bertan

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

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