【问题标题】:Android: How to get XML values inside a parent tagAndroid:如何在父标签中获取 XML 值
【发布时间】:2011-05-18 09:09:14
【问题描述】:

我想知道如何在我的 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 开发的新手,非常感谢您的帮助! :)

【问题讨论】:

    标签: java android xml parsing sax


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 感谢您的回复,但您知道如何使用 sax 解析器吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多