Android:如何在父标记内获取XML值

时间:2011-05-18 09:09:14

标签: java android xml parsing sax

我想知道如何在我的xml文件中检索电话簿标签内的值:

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<SyncDataResponse>
    <Videos>
        <PhonebookVideo>
            <firstname>V Michael</firstname> 
            <lastname>V De Leon</lastname> 
            <Address>V 5, Cat Street</Address> 
            <FileURL>http://cloud.somedomain.com/jm/26.flv</FileURL> 
        </PhonebookVideo>
        <PhonebookVideo>
            <firstname>V John</firstname> 
            <lastname>V Smith</lastname> 
            <Address>V 6, Dog Street</Address> 
            <FileURL>http://cloud.somedomain.com/jm/27.flv</FileURL> 
        </PhonebookVideo>
    </Videos>
    <Phonebook>
        <PhonebookEntry>
            <firstname>Michael</firstname> 
            <lastname>De Leon</lastname> 
            <Address>5, Cat Street</Address> 
            <FileURL>http://www.technobuzz.net/wp-content/uploads/2009/09/Android-Emulator.jpg</FileURL> 
        </PhonebookEntry>
        <PhonebookEntry>
            <firstname>John</firstname> 
            <lastname>Smith</lastname> 
            <Address>6, Dog Street</Address> 
            <FileURL>http://www.cellphonehits.net/uploads/2008/10/android_openmoko.jpg</FileURL> 
        </PhonebookEntry>
        <PhonebookEntry>
            <firstname>Jember</firstname> 
            <lastname>Dowry</lastname> 
            <Address>7, Monkey Street</Address> 
            <FileURL>http://www.techdigest.tv/android.jpg</FileURL> 
        </PhonebookEntry>
        <PhonebookEntry>
            <firstname>Manilyn</firstname> 
            <lastname>Bulambao</lastname> 
            <Address>8, Tiger Street</Address> 
            <FileURL>http://www.ctctlabs.com/staticContent/weblog/xml-android.png</FileURL> 
        </PhonebookEntry>
    </Phonebook>
    <Audios>
        <PhonebookAudio>
            <firstname>A Michael</firstname> 
            <lastname>A De Leon</lastname> 
            <Address>A 5, Cat Street</Address> 
            <FileURL>http://cloud.somedomain.com/jm/a1.mp3</FileURL> 
        </PhonebookAudio>
        <PhonebookAudio> 
            <firstname>A John</firstname> 
            <lastname>A Smith</lastname> 
            <Address>A 6, Dog Street</Address> 
            <FileURL>http://cloud.somedomain.com/jm/a2.mp3</FileURL> 
        </PhonebookAudio>
        <PhonebookAudio> 
            <firstname>A Jember</firstname> 
            <lastname>A Dowry</lastname> 
            <Address>A 7, Monkey Street</Address> 
            <FileURL>http://cloud.somedomain.com/jm/a3.mp3</FileURL> 
        </PhonebookAudio>
    </Audios>
</SyncDataResponse>

我的代码:

在我的主要活动(ParsingXML.java)上,我有类似的东西:

/* Create a new TextView to display the parsingresult later. */
TextView tv = new TextView(this);
tv.setText("This is the parsing program...");


try {
  /* Create a URL we want to load some xml-data from. */
  URL url = new URL("http://cloud.somedomain.com/jm/sampleXML.xml");
  url.openConnection();
  /* Get a SAXParser from the SAXPArserFactory. */
  SAXParserFactory spf = SAXParserFactory.newInstance();
  SAXParser sp = spf.newSAXParser();

  /* Get the XMLReader of the SAXParser we created. */
  XMLReader xr = sp.getXMLReader();
  /* Create a new ContentHandler and apply it to the XML-Reader*/
  ExampleHandler myExampleHandler = new ExampleHandler();
  xr.setContentHandler(myExampleHandler);

  /* Parse the xml-data from our URL. */
  xr.parse(new InputSource(url.openStream()));
  /* Parsing has finished. */

  /* Our ExampleHandler now provides the parsed data to us. */
  List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();

  /* Set the result to be displayed in our GUI. */
  //tv.setText(parsedExampleDataSet.toString());

  String currentFile = null;
  String currentFileURL = null;
  Iterator i;
  i = parsedExampleDataSet.iterator();
  ParsedExampleDataSet dataItem;
  while(i.hasNext()){

       dataItem = (ParsedExampleDataSet) i.next();
       tv.append("\n" + dataItem.getfirstname());
       tv.append("\n" + dataItem.getlastname());
       tv.append("\n" + dataItem.getAddress());
       tv.append("\n" + dataItem.getFileURL());

       if(dataItem.getparenttag() == "Video"){
            currentFile = dataItem.getfirstname() + ".flv";
       }else if(dataItem.getparenttag() == "PhoneBook"){
            currentFile = dataItem.getfirstname() + ".jpg";
       }else if(dataItem.getparenttag() == "Audio"){
           currentFile = dataItem.getfirstname() + ".mp3";
       }

       currentFileURL = dataItem.getFileURL();
       startDownload(currentFile, currentFileURL);
  }

} catch (Exception e) {
  /* Display any Error to the GUI. */
  tv.setText("Error: " + e.getMessage());

}
/* Display the TextView. */
this.setContentView(tv);

我在我的处理程序(ExampleHandler.java)上有这个:

 private StringBuilder mStringBuilder = new StringBuilder();

 private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet();
 private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>();

 // ===========================================================
 // Getter & Setter
 // ===========================================================

 public List<ParsedExampleDataSet> getParsedData() {
      return this.mParsedDataSetList;
 }

 // ===========================================================
 // Methods
 // ===========================================================

 /** Gets be called on opening tags like:
  * <tag>
  * Can provide attribute(s), when xml was like:
  * <tag attribute="attributeValue">*/
 @Override
 public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    if (localName.equals("PhonebookEntry")) {
        this.mParsedExampleDataSet = new ParsedExampleDataSet();
    }

 }

 /** Gets be called on closing tags like:
  * </tag> */
 @Override
 public void endElement(String namespaceURI, String localName, String qName)
           throws SAXException {


      if (localName.equals("PhonebookEntry")) {
           this.mParsedDataSetList.add(mParsedExampleDataSet);
           mParsedExampleDataSet.setparenttag("PhoneBook");
      }else if (localName.equals("firstname")) {
           mParsedExampleDataSet.setfirstname(mStringBuilder.toString().trim());
      }else if (localName.equals("lastname"))  {
          mParsedExampleDataSet.setlastname(mStringBuilder.toString().trim());
      }else if(localName.equals("Address"))  {
          mParsedExampleDataSet.setAddress(mStringBuilder.toString().trim());
      }else if(localName.equals("FileURL")){
          mParsedExampleDataSet.setFileURL(mStringBuilder.toString().trim());
      }

      mStringBuilder.setLength(0);
 }

 /** Gets be called on the following structure:
  * <tag>characters</tag> */
 @Override
public void characters(char ch[], int start, int length) {
      mStringBuilder.append(ch, start, length);
}

我有这个用于dataSet(ParsedExampleDataSet.java)

    private String parenttag = null;
    private String firstname = null;
    private String lastname=null;
    private String Address=null;
    private String FileURL=null;

    //Parent tag
    public String getparenttag() {
         return parenttag;
    }
    public void setparenttag(String parenttag) {
         this.parenttag = parenttag;
    }

    //Firstname
    public String getfirstname() {
         return firstname;
    }
    public void setfirstname(String firstname) {
         this.firstname = firstname;
    }

    //Lastname
    public String getlastname(){
        return lastname;
    }
    public void setlastname(String lastname){
        this.lastname=lastname;
    }

    //Address
    public String getAddress(){
        return Address;
    }
    public void setAddress(String Address){
        this.Address=Address;
    }

    //FileURL
    public String getFileURL(){
        return FileURL;
    }
    public void setFileURL(String FileURL){
        this.FileURL=FileURL;
    }

此代码的输出是,由于里面有4条记录,预计会返回4条记录。 是的,它返回了4条记录,但它只是正确地检索了前三条记录 然后第四条记录不正确,第四条记录实际上是PhonebookAudio标签中的记录。

就是这样:

This is the parsing program...

Michael
De Leon
5, Cat Street
http://www.technobuzz.net/wp-content/uploads/2009/09/Android-Emulator.jpg

John
Smith
6, Dog Street
http://www.cellphonehits.net/uploads/2008/10/android_openmoko.jpg

Jember
Dowry
7, Monkey Street
http://www.techdigest.tv/android.jpg

A Jember
A Dowry
A 7, Monkey Street
http://cloud.somedomain.com/jm/a3.mp3

我是java和android dev的新手,非常感谢你们提供任何帮助! :)

2 个答案:

答案 0 :(得分:0)

将xml作为InputStream打开(在下面的代码中称为“is” 然后

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

        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while((current = bis.read()) != -1){
              baf.append((byte)current);
         }
        String ret = new String(baf.toByteArray(),GlobalVars.webencoding);
       */ 
        doc = db.parse(urlConnection.getInputStream());
        String desc = "";

        if(doc.getElementsByTagName("description").getLength()>0){
            //do something like that
            int len = doc.getElementsByTagName("description").getLength();
            desc = doc.getElementsByTagName("description").item(len-1).getFirstChild().getNodeValue();

        }

答案 1 :(得分:0)

PhoneBookAudio中的名字,姓氏,地址和网址正在破坏上一个PhoneBookEntry的详细信息。

要么跟踪你所处的状态,所以当你输入你关心现在正在发生的事情并在你离开时清除注释时做一个注释,或者在结束时添加一个“this.mParsedDataSetList = null”。你的PhoneBookEntry的endElement处理程序。