Android:如何获取父标签内的 XML 值

发布于 2024-11-08 14:37:51 字数 9311 浏览 0 评论 0原文

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

我有这个数据集 (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 条记录,但它只正确检索了前 3 条记录 然后第四条记录不正确,第四条记录实际上是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 开发有点陌生,非常感谢您的帮助! :)

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

<?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:

/* 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):

 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)

    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.

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! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

贵在坚持 2024-11-15 14:37:51

PhoneBookAudio 中的名字、姓氏、地址和 url 破坏了最后一个 PhoneBookEntry 的详细信息。

跟踪您所处的状态,因此在输入时记下您关心现在发生的事情,并在离开时清除注释,或者在 endElement 处理程序末尾添加“this.mParsedDataSetList = null”对于 PhoneBookEntry。

The firstname, lastname, address and url in the PhoneBookAudio are clobbering the details from the last 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.

掌心的温暖 2024-11-15 14:37:51

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

        }

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

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

        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文