2012-11-16 54 views
0

一個XML文件我有這個XML文件:解析Android中

<maths> 

<mathametician> 
<id>101</id> 
<name>kurt</name> 
<age>75</age> 
</mathametician> 

<mathametician> 
<id>102</id> 
<name>david</name> 
<age>62</age> 
</mathametician> 

</maths> 

我可以使用此代碼成功獲取數據:

 try { 
      InputStream raw = this.getApplicationContext().getAssets() 
        .open("maths.xml"); 

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder db = dbf.newDocumentBuilder(); 

      Document doc = db.parse(raw); 
      doc.getDocumentElement().normalize(); 
      NodeList nodeList = doc.getElementsByTagName("mathametician"); 

      for (int i = 0; i < nodeList.getLength(); i++) { 

       Node node = nodeList.item(i); 
       Element fstElmnt = (Element) node; 

       NodeList websiteList = fstElmnt.getElementsByTagName("age"); 
       Element websiteElement = (Element) websiteList.item(0); 
       websiteList = websiteElement.getChildNodes(); 

       Toast.makeText(getApplicationContext(), 
         websiteList.item(0).getNodeValue(), Toast.LENGTH_SHORT) 
         .show(); 
      } 

我的問題是:爲什麼我不能得到數據後直接:

NodeList websiteList = fstElmnt.getElementsByTagName("age"); 

我得到空的結果,除非我寫:

Element websiteElement = (Element) websiteList.item(0); 
websiteList = websiteElement.getChildNodes(); 

謝謝。

回答

1

解析器類:

public final class SampleParser{ 


    final static String ROOT_NODE = "maths"; 
    final static String ELEMENT_MATHAMETICIAN = "mathametician"; 
    final static String ELEMENT_ID = "id"; 
    final static String ELEMENT_NAME = "name"; 
    final static String ELEMENT_AGE = "age"; 

    private static final String TAG="SampleParser"; 

    /** 
    * Intentionally commented 
    */ 
    private SampleParser() {} 

    /** 
    * @param response The XML string which represents the complete news data 
    * @return news The complete data 
    */ 
    public static Maths parse(String response) { 
     SAXParserFactory spf = SAXParserFactory.newInstance(); 
     SAXParser sp; 
     try { 
      sp = spf.newSAXParser(); 
      XMLReader xr = sp.getXMLReader(); 
      SampleDataHandler dataHandler = new SampleDataHandler(); 
      xr.setContentHandler(dataHandler); 
      InputSource source = new InputSource(new StringReader(response)); 
      xr.parse(source); 
      Maths result = dataHandler.getData(); 
      return result; 
     } catch (ParserConfigurationException e) { 
      Log.e(TAG, "parse", e); 
     } catch (SAXException e) { 
      Log.e(TAG, "parse", e); 
     } catch (IOException e) { 
      Log.e(TAG, "parse", e); 
     } 
     return null; 
    } 

    static class SampleDataHandler extends DefaultHandler { 
     /** 
     * 
     */ 
     private static final String TAG="NewsDataHandler"; 
     /** 
     * 
     */ 
     private Maths data; 
     /** 
     * 
     */ 
     private Mathematician tempElement; 
     /** 
     * 
     */ 
     private boolean readingAge; 
     /** 
     * 
     */ 
     private boolean readingName; 
     /** 
     * 
     */ 
     private boolean readingID; 
     /** 
     * 
     */ 
     public Maths getData(){ 
      return data; 
     } 

     /* 
     * (non-Javadoc) 
     * 
     * @see org.xml.sax.helpers.DefaultHandler#endDocument() 
     */ 
     @Override 
     public void endDocument() throws SAXException { 
      Log.d(TAG, "endDocument Finished parsing response"); 
     } 

     /* 
     * (non-Javadoc) 
     * 
     * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, 
     * java.lang.String, java.lang.String) 
     */ 
     @Override 
     public void endElement(String uri, String localName, String qName) 
       throws SAXException { 
      if(qName.equalsIgnoreCase(ELEMENT_MATHAMETICIAN)){ 
       data.addMathematician(tempElement); 
      }else if(qName.equalsIgnoreCase(ELEMENT_ID)){ 
       readingID = false; 
      }else if(qName.equalsIgnoreCase(ELEMENT_NAME)){ 
       readingName = false; 
      }else if(qName.equalsIgnoreCase(ELEMENT_AGE)){ 
       readingAge = false; 
      } 
     } 

     /* 
     * (non-Javadoc) 
     * 
     * @see org.xml.sax.helpers.DefaultHandler#startDocument() 
     */ 
     @Override 
     public void startDocument() throws SAXException { 
      data = new Maths(); 
      Log.d(TAG, "startDocument Started parsing response"); 
     } 

     /* 
     * (non-Javadoc) 
     * 
     * @see 
     * org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, 
     * java.lang.String, java.lang.String, org.xml.sax.Attributes) 
     */ 
     @Override 
     public void startElement(String uri, String localName, String qName, 
       Attributes attributes) throws SAXException { 
      if(qName.equalsIgnoreCase(ROOT_NODE)){ 
       //data.setData(new ArrayList<NewsElement>()); 
      }else if(qName.equalsIgnoreCase(ELEMENT_AGE)){ 
       readingAge=true;     
      }else if(qName.equalsIgnoreCase(ELEMENT_MATHAMETICIAN)){ 
       tempElement = new Mathematician(); 
      }else if(qName.equalsIgnoreCase(ELEMENT_ID)){ 
       readingID=true; 
      }else if(qName.equalsIgnoreCase(ELEMENT_NAME)){ 
       readingName=true; 
      } 
     } 

     /* 
     * (non-Javadoc) 
     * 
     * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int) 
     */ 
     @Override 
     public void characters(char[] ch, int start, int length) 
       throws SAXException { 
      String chars = new String(ch, start, length);  
      chars = chars.trim(); 
      if(readingID){ 
       try{ 
        tempElement.setId(Integer.parseInt(chars)); 
       }catch(Exception e){ 
        Log.e(TAG, "characters[Parsing ID]", e); 
        tempElement.setId(-1); 
       } 
      } 
      else if(readingAge){ 
       try{ 
        tempElement.setAge(Integer.parseInt(chars)); 
       }catch(Exception e){ 
        Log.e(TAG, "characters[Parsing Age]", e); 
        tempElement.setAge(-1); 
       } 
      }else if(readingName){ 
       tempElement.setName(chars); 
      } 
     } 
    } 
} 

使用的POJO對象:

public class Maths { 

    private ArrayList<Mathematician> mathematicians; 

    /** 
    * @return the mathematicians 
    */ 
    public ArrayList<Mathematician> getMathematicians() { 
     return mathematicians; 
    } 

    /** 
    * @param mathematicians the mathematicians to set 
    */ 
    public void setMathematicians(ArrayList<Mathematician> mathematicians) { 
     this.mathematicians = mathematicians; 
    } 

    /** 
    * @param item The item to add 
    */ 
    public void addMathematician(Mathematician item){ 
     if(null == mathematicians){ 
      mathematicians = new ArrayList<Mathematician>(); 
     } 
     mathematicians.add(item); 
    } 
} 

public class Mathematician { 

    private int id; 
    private String name; 
    private int age; 
    /** 
    * @return the id 
    */ 
    public int getId() { 
     return id; 
    } 
    /** 
    * @param id the id to set 
    */ 
    public void setId(int id) { 
     this.id = id; 
    } 
    /** 
    * @return the name 
    */ 
    public String getName() { 
     return name; 
    } 
    /** 
    * @param name the name to set 
    */ 
    public void setName(String name) { 
     this.name = name; 
    } 
    /** 
    * @return the age 
    */ 
    public int getAge() { 
     return age; 
    } 
    /** 
    * @param age the age to set 
    */ 
    public void setAge(int age) { 
     this.age = age; 
    } 
} 

我跑了它,它工作正常。希望這可以幫助。

+0

您可以使用[簡單的XML(http://www.google.ru/url?sa=t&source=web&cd=2&ved=0CCQQFjAB&url=http://simple.sourceforge.net/&ei=o2nvTbPJHMKe-QaTsrmECA&usg=AFQjCNE40FfELo6ftmZBNkdIi9a -W5QIzQ&sig2 = VFd2mp8YdqVBSD-pmEwsvw)讀取對象中的xml文件,修改其狀態並將其寫回。 –