2013-04-27 79 views
-1

我正在做我自己的Android應用程序,我正在煩惱。在Android中解析XML DOMDOWNE

我的應用程序讀取和寫入一個XML文件。 我有這樣的代碼從SD卡打開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; 

    } 

我打開從資產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(); 
      } 
    } 

我不知道爲什麼一種方法適用於添加信息,不適用於閱讀。 感謝

回答

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

} 
+0

這兩種方法都不適合我D: – 2013-04-28 13:18:25

1

解決。該守則運作良好。在來自SdCard的XML文件中,我有fecha(date)和monto(double)的String值。我刪除了thoose無效記錄,現在工作正常