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

时间:2022-10-27 10:27:39

I wonder how can I retrieve the values inside the Phonebook tags here in my xml file:

我想知道如何在我的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>

My code:

On my main activity (ParsingXML.java), I have something like this:

在我的主要活动(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);

I have this on my handler (ExampleHandler.java):

我在我的处理程序(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);
}

And I have this for the dataSet (ParsedExampleDataSet.java)

我有这个用于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;
    }

The output of this code is, since has 4 records inside, it is expected to return 4 records. And yes, it returned 4 records but it just retrieves the first three records correctly and then the fourth record is incorrect, the fourth record is actually the record in the PhonebookAudio tag.

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

It is exactly like this:

它完全是这样的:

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

I'm kinda new to java and android dev, thank you so much in advanced for any help! :)

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

2 个解决方案

#1


0  

The firstname, lastname, address and url in the PhoneBookAudio are clobbering the details from the last PhoneBookEntry.

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

Either keep track of which state you're in, so make a note when you enter that you care about what's happening now and clear the note when you leave , or add a "this.mParsedDataSetList = null" at the end of your endElement handler for a PhoneBookEntry.

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

#2


0  

open the xml as InputStream (called "is" in the code below then

打开xml作为InputStream(在下面的代码中称为“是”)

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  

The firstname, lastname, address and url in the PhoneBookAudio are clobbering the details from the last PhoneBookEntry.

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

Either keep track of which state you're in, so make a note when you enter that you care about what's happening now and clear the note when you leave , or add a "this.mParsedDataSetList = null" at the end of your endElement handler for a PhoneBookEntry.

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

#2


0  

open the xml as InputStream (called "is" in the code below then

打开xml作为InputStream(在下面的代码中称为“是”)

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();

        }