Android: How Can I display all XML values of same tag name

前端 未结 4 1605
Happy的楠姐
Happy的楠姐 2021-01-20 15:43

I have the ff. XML from a URL:

 

    
                 


        
相关标签:
4条回答
  • 2021-01-20 16:06

    You were close. Since you have many PhoneBookeEntrys you need to store them somewhere:

    public class ExampleHandler extends DefaultHandler{
    
     // ===========================================================
     // Fields
     // ===========================================================
    
     private boolean in_outertag = false;
     private boolean in_innertag = false;
     private boolean in_firstname = false;
     private boolean in_lastname= false;
     private boolean in_Address=false;
    
     private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
     private List<ParsedExampleDataSet> allSets = new ArrayList<ParsedExampleDataSet>();
    
     // ===========================================================
     // Getter & Setter
     // ===========================================================
    
     public ParsedExampleDataSet getParsedData() {
          return this.myParsedExampleDataSet;
     }
    
     // ===========================================================
     // 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("PhoneBook")) {
            this.in_outertag = true;
        }else if (localName.equals("PhonebookEntry")) {
            this.in_innertag = true;
            this.myParsedExampleDataSet = new ParsedExampleDataSet();
        }else if (localName.equals("firstname")) {
            this.in_firstname = true;
        }else if (localName.equals("lastname"))  {
            this.in_lastname= true;
        }else if(localName.equals("Address"))  {
            this.in_Address= true;
        } 
    
     }
    
     /** Gets be called on closing tags like:
      * </tag> */
     @Override
     public void endElement(String namespaceURI, String localName, String qName)
               throws SAXException {
          if (localName.equals("Phonebook")) {
               this.in_outertag = false;
          }else if (localName.equals("PhonebookEntry")) {
               this.in_innertag = false;
               allSets.add(myParsedExampleDataSet);
          }else if (localName.equals("firstname")) {
               this.in_firstname = false;
          }else if (localName.equals("lastname"))  {
              this.in_lastname= false;
          }else if(localName.equals("Address"))  {
              this.in_Address= false;
          }
     }
    
     /** Gets be called on the following structure:
      * <tag>characters</tag> */
     @Override
    public void characters(char ch[], int start, int length) {
          if(this.in_firstname){
          myParsedExampleDataSet.setfirstname(new String(ch, start, length));
          }
          if(this.in_lastname){
          myParsedExampleDataSet.setlastname(new String(ch, start, length));
          }
          if(this.in_Address){
              myParsedExampleDataSet.setAddress(new String(ch, start, length));
          }
    }
    }
    
    0 讨论(0)
  • 2021-01-20 16:16

    I found an XML tutorial online here and editied it to work with your XML file. Below is the code. For the sake of testing it on my machine, I've sourced the XML file from a local file rather than online, but it shouldn't be too hard to work out.

    This should hopefully point you in the right direction.

    package phonebook;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    import java.io.File;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    
    public class program {
        public static void main(String argv[]) {
    
              try {
                  File file = new File("phonebook.xml");
                  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                  DocumentBuilder db = dbf.newDocumentBuilder();
                  Document doc = db.parse(file);
                  doc.getDocumentElement().normalize();
                  System.out.println("Root element " + doc.getDocumentElement().getNodeName());
                  NodeList nodeLst = doc.getElementsByTagName("PhonebookEntry");
                  System.out.println("Information of all entries");
    
                  for (int s = 0; s < nodeLst.getLength(); s++) {
    
                    Node fstNode = nodeLst.item(s);
    
                    if (fstNode.getNodeType() == Node.ELEMENT_NODE)
                    {
                      Element fstElmnt = (Element) fstNode;
    
                      // Firstname
                      NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
                      Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                      NodeList fstNm = fstNmElmnt.getChildNodes();
                      System.out.println("First Name : "  + ((Node) fstNm.item(0)).getNodeValue());
    
                      // Lastname
                      NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
                      Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                      NodeList lstNm = lstNmElmnt.getChildNodes();
                      System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
    
                      // Address
                      NodeList addrNmElmntLst = fstElmnt.getElementsByTagName("Address");
                      Element addrNmElmnt = (Element) addrNmElmntLst.item(0);
                      NodeList addrNm = addrNmElmnt.getChildNodes();
                      System.out.println("Address : " + ((Node) addrNm.item(0)).getNodeValue());
                    }
                  }
              } catch (Exception e) {
                e.printStackTrace();
              }
             }
    }
    
    0 讨论(0)
  • 2021-01-20 16:25

    The other responses have already pointed out that you require a list to store all the ParsedExampleDataSet objects gotten from the XML.

    But I want to point your attention to another thing about XML handlers which may bite you only later (and randomly). The characters method is not a good place to assign the values found between tags in you XML, because the characters method is not guaranteed to return all the characters in an element at once. It may be called multiple times within the same element to report characters found so far. With your implementation as it is right now, you will end up with missing data and wonder what is going on.

    That said, what I would do it use a StringBuilder to accumulate your characters and then assign them in an endElement(...) call. Like so:

    public class ExampleHandler extends DefaultHandler{
    
     // ===========================================================
     // Fields
     // ===========================================================
    
     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);
          }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());
          }
          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);
    }
    }
    

    You can then retrieve the list of ParsedExampleDataSets in your activity and either display in multiple text views or only in one. Your Activity.onCreate(...) method may look like:

    /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle icicle) {
             super.onCreate(icicle);
    
             /* Create a new TextView to display the parsingresult later. */
             TextView tv = new TextView(this);
             try {
                  /* Create a URL we want to load some xml-data from. */
                  URL url = new URL("http://somedomain.com/jm/sampleXML.xml");
                  URLConnection ucon = url.openConnection();
    
                  /* Create a new ContentHandler and apply it to the XML-Reader*/
                  ExampleHandler myExampleHandler = new ExampleHandler();
    
                  //remember to import android.util.Xml
                  Xml.parse(url.openStream(), Xml.Encoding.UTF_8, myExampleHandler);
    
    
                  /* Our ExampleHandler now provides the parsed data to us. */
                  List<ParsedExampleDataSet> parsedExampleDataSetList =
                                                myExampleHandler.getParsedData();
    
                  /* Set the result to be displayed in our GUI. */
                  for(ParsedExampleDataSet parsedExampleDataSet : parsedExampleDataSetList){
                      tv.append(parsedExampleDataSet.toString());
                  }
    
             } catch (Exception e) {
                  /* Display any Error to the GUI. */
                  tv.setText("Error: " + e.getMessage());
    
             }
             /* Display the TextView. */
             this.setContentView(tv);
        }
    
    0 讨论(0)
  • 2021-01-20 16:28

    You only have one ParsedExampleDataSet object in your handler, so there's only room to store one entry. Change ExampleHandler to have an ArrayList<ParsedExampleDataSet> results and also a ParsedExampleDataSet currentSet. Inside startElement, when you see the PhoneBook tag, set currentSet to a new instance of ParsedExampleDataSet and add it to results. After parsing, results should contain everything you want.

    0 讨论(0)
提交回复
热议问题