-1

我正在做我自己的 Android 应用程序,我感到很麻烦。

我的应用程序读取和写入 XML 文件。我有这段代码可以从 SDCard 打开 XML 文件:

public void abrirSD()
    {
        try{
             DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
             DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
             dom = docBuilder.parse(new File("mnt/sdcard/gastos.xml"));


        }
        catch (Exception e) {
            e.printStackTrace();
            }
    }

它适用于向文件添加信息的代码:

public boolean nuevo(Gasto clGasto)
    {
        this.abrirSD();

        String strDesc=clGasto.getDescripcion();
        String strMonto=Double.toString(clGasto.getMonto());
        java.util.Date date = new java.util.Date();
        java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("dd/MM/yyyy");
        String strFecha = sdf.format(date);

        Node gastos=dom.getFirstChild();
        Node gasto= dom.createElement("gasto");
        Element descripcion= dom.createElement("descripcion");
        descripcion.appendChild(dom.createTextNode(strDesc));
        gasto.appendChild(descripcion);
        Element monto= dom.createElement("monto");
        monto.appendChild(dom.createTextNode(strMonto));
        gasto.appendChild(monto);
        Element fecha= dom.createElement("fecha");
        fecha.appendChild(dom.createTextNode(strFecha));
        gasto.appendChild(fecha);
        gastos.appendChild(gasto);
        try
        {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StreamResult streamResult = new StreamResult(new File("mnt/sdcard/gastos.xml"));
            DOMSource source = new DOMSource(dom);
            transformer.transform(source, streamResult);
            return true;
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

但它不适用于读取信息

public List<Gasto> getAll()
    {

        List<Gasto> gastos = new ArrayList<Gasto>();
        this.abrirSD();

        //this.abrirArchivo();

        //Nos posicionamos en el nodo principal del árbol (<gastos>)
        Element root = dom.getDocumentElement();

        //Localizamos todos los elementos <item>
        NodeList items = root.getElementsByTagName("gasto");

        //Recorremos la lista de gastos
        for(int i=0;i<items.getLength();i++)
        {
            Gasto gasto= new Gasto();

            //Obtenemos el gasto actual
            Node item=items.item(i);

            //Obtenemos la lista de datos del gasto actual
            NodeList datosGasto = item.getChildNodes();

            //Procesamos cada dato de el gasto actual
            for (int j=0; j<datosGasto.getLength(); j++)
            {

                //asigno a dato el item actual
                Node dato= datosGasto.item(j);

                //Obtengo la etiqueta el item actual
                String etiqueta= dato.getNodeName();

                if(etiqueta.equals("descripcion"))
                {
                    String texto= obtenerTexto(dato);
                    gasto.setDescripcion(texto);

                }
                else if(etiqueta.equals("monto"))
                {
                    gasto.setMonto(Double.parseDouble(dato.getFirstChild().getNodeValue()));
                }

                else if(etiqueta.equals("fecha"))
                {
                    java.util.Date fecha= new Date();
                    SimpleDateFormat formatoDeFecha = new SimpleDateFormat("dd/MM/yyyy");
                    try
                    {
                    fecha= formatoDeFecha.parse(dato.getFirstChild().getNodeValue());
                    }
                    catch(Exception e)
                    {

                    }
                    gasto.setFecha(fecha);


                }
            }
            gastos.add(gasto);
        }

        return gastos;

    }

我有这个从 Assets 打开 XML 文件的其他代码,它与读取代码(getAll 方法)一起使用。

public void abrirArchivo()
    {       
        //Cargo el archivo xml en una variable Document
        try
        {                   
        AssetManager assManager = context.getAssets();

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();    
        dom = dBuilder.parse(assManager.open("gastos.xml"));
        }
        catch (Exception e) {
            e.printStackTrace();
            }
    }

我不知道为什么一种方法适用于添加信息而不适用于读取。谢谢

4

2 回答 2

1

解决了。守则运作良好。在 SdCard 的 XML 文件中,我有 fecha(date) 和 monto(double) 的 String 值。我删除了那些无效的记录,现在它工作正常

于 2013-04-28T14:36:38.927 回答
0

看看这个——

package com.example.playrecordedvideo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XMLParser {
    Document docData;
    public boolean ReadXmlFile(String filePath)
    {
        try {
            String Data="";
            File fIN = new File(filePath);

            if (fIN.exists()) 
            {
                StringBuffer fileData = new StringBuffer(1000);
                BufferedReader reader = new BufferedReader(
                        new FileReader(filePath));
                char[] buf = new char[1024];
                int numRead=0;

                while((numRead=reader.read(buf)) != -1){            
                    String readData = String.valueOf(buf, 0, numRead);
                    fileData.append(readData);              
                    buf = new char[1024];
                }

                reader.close();   
                Data= fileData.toString();

            }
            else
            {

                return false;
            }

            docData = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            try 
            {           
                DocumentBuilder db = dbf.newDocumentBuilder();          
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(Data));
                docData = db.parse(is);         
            } catch (ParserConfigurationException e) {          

                return false;
            } catch (SAXException e) {          

                return false;
            } catch (IOException e) {           

                return false;
            }
            return true;
        } catch (Exception e) {

            return false;
        }
    }

    public boolean ReadXmlData(String Data)
    {
        try {

            docData = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            try {           
                DocumentBuilder db = dbf.newDocumentBuilder();          
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(Data));
                docData = db.parse(is);         
            } catch (ParserConfigurationException e) {          

                return false;
            } catch (SAXException e) {          

                return false;
            } catch (IOException e) {           

                return false;
            }

            return true;
        } catch (Exception e) {

            return false;
        }
    }

    public boolean WriteXml(String fileName)
    {
        try
        {
            //write original temp file

                String tempFile=fileName;

                Transformer transformer = TransformerFactory.newInstance().newTransformer();  
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");            
                StreamResult result = new StreamResult(new FileWriter(tempFile));  
                DOMSource source = new DOMSource(docData);  
                transformer.transform(source, result);

            return true;
        }
        catch (Exception e) {

            return false;
        }
    }

    public void SetValue(String ColumnName,String Value)
    {
        try
        {           
            docData.getElementsByTagName(ColumnName).item(0).getFirstChild().setNodeValue(Value);
        }
        catch (Exception e) {

        }
    }

    public String GetValue(String ColumnName)
    {
        String Value="ERROR"; 

        try
        {
            Value=docData.getElementsByTagName(ColumnName).item(0).getFirstChild().getNodeValue();
        }
        catch (Exception e) {

        }
        return Value;
    }   


    public int getRowsLength()
    {
        try
        {           
            return docData.getElementsByTagName("Data").getLength();
        }
        catch (Exception e) {

        }
        return 0;
    }

    public boolean NewRow(String id,String time)
    {
        try {
            Element baseRoot; 
            baseRoot = docData.getDocumentElement(); 

            Element root = docData.createElement("Data"); 
            baseRoot.appendChild(root); 

            Element child = docData.createElement("ID"); 
            root.appendChild(child); 

            Text text = docData.createTextNode(id); 
            child.appendChild(text); 

            child = docData.createElement("TIME"); 
            root.appendChild(child);

            text = docData.createTextNode(time); 
            child.appendChild(text);            

            return true;
        } catch (Exception e) {         
            return false;
        }

    }   

    public void SetValue(String ColumnName,String Value,int index)
    {
        try
        {           
            docData.getElementsByTagName(ColumnName).item(index).getFirstChild().setNodeValue(Value);
        }
        catch (Exception e) {

        }
    }

    public String GetValue(String ColumnName,int index)
    {
        String Value="ERROR"; 
        try
        {
            Value=docData.getElementsByTagName(ColumnName).item(index).getFirstChild().getNodeValue();
        }
        catch (Exception e) {

        }
        return Value;
    }   

}
于 2013-04-28T05:28:09.203 回答