Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android:如何显示相同标记名的所有XML值_Java_Android_Xml_Url_Sax - Fatal编程技术网

Java Android:如何显示相同标记名的所有XML值

Java Android:如何显示相同标记名的所有XML值,java,android,xml,url,sax,Java,Android,Xml,Url,Sax,我有最新消息。来自URL的XML: <?xml version="1.0" encoding="ISO-8859-1" ?> <Phonebook> <PhonebookEntry> <firstname>Michael</firstname> <lastname>De Leon</lastname> <Address>5, Cat Str

我有最新消息。来自URL的XML:

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<Phonebook>
    <PhonebookEntry>
        <firstname>Michael</firstname> 
        <lastname>De Leon</lastname> 
        <Address>5, Cat Street</Address> 
    </PhonebookEntry>
    <PhonebookEntry>
        <firstname>John</firstname> 
        <lastname>Smith</lastname> 
        <Address>6, Dog Street</Address> 
    </PhonebookEntry>
</Phonebook>
ExampleHandler.java

package com.example.parsingxml;

import java.net.Proxy;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class ParsingXML extends Activity {



    /** 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();
              /* 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. */
              ParsedExampleDataSet parsedExampleDataSet =
                                            myExampleHandler.getParsedData();

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

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

         }
         /* Display the TextView. */
         this.setContentView(tv);
    }
}
package com.example.parsingxml;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


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

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

     public ParsedExampleDataSet getParsedData() {
          return this.myParsedExampleDataSet;
     }

     // ===========================================================
     // Methods
     // ===========================================================
     @Override
     public void startDocument() throws SAXException {
          this.myParsedExampleDataSet = new ParsedExampleDataSet();
     }

     @Override
     public void endDocument() throws SAXException {
          // Nothing to do
     }

     /** 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;
        }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;
          }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));
          }
    }
}
package com.example.parsingxml;

public class ParsedExampleDataSet {
    private String firstname = null;
    private String lastname=null;
    private String Address=null;


    //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;
    }

    public String toString(){
         return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address;

    }
}

我是java和android开发的新手,非常感谢您的帮助!:)

处理程序中只有一个ParsedExampleDataSet对象,因此只有空间存储一个条目。将ExampleHandler更改为具有
ArrayList results
ParsedExampleDataSet currentSet
。在
startElement
内部,当您看到
PhoneBook
标签时,将
currentSet
设置为
ParsedExampleDataSet
的新实例,并将其添加到
结果中。解析后,
结果
应该包含您想要的所有内容。

您已经接近了。由于您有许多
phonebookeentry
,因此需要将它们存储在某个位置:

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));
      }
}
}
公共类ExampleHandler扩展了DefaultHandler{
// ===========================================================
//田地
// ===========================================================
私有布尔in_outertag=false;
_innertag中的私有布尔值=false;
firstname中的私有布尔值=false;
_lastname中的私有布尔值=false;
地址中的私有布尔值=false;
private ParsedExampleDataSet myParsedExampleDataSet=new ParsedExampleDataSet();
private List allset=new ArrayList();
// ===========================================================
//吸气剂和塞特
// ===========================================================
公共ParsedExampleDataSet getParsedData(){
返回此.myParsedExampleDataSet;
}
// ===========================================================
//方法
// ===========================================================
/**在开始标记上调用的获取,如:
* 
*当xml类似于以下内容时,可以提供属性:
* */
@凌驾
public void startElement(字符串namespaceURI、字符串localName、字符串qName、属性atts)引发异常{
if(localName.equals(“电话簿”)){
this.in_outertag=true;
}else if(localName.equals(“PhonebookEntry”)){
this.in_innertag=true;
this.myParsedExampleDataSet=新的ParsedExampleDataSet();
}else if(localName.equals(“firstname”)){
this.in_firstname=true;
}else if(localName.equals(“lastname”)){
this.in_lastname=true;
}else if(localName.equals(“地址”)){
此.in_Address=true;
} 
}
/**在关闭标记上调用的控件,如:
*  */
@凌驾
public void endElement(字符串namespaceURI、字符串localName、字符串qName)
抛出SAX异常{
if(localName.equals(“电话簿”)){
this.in_outertag=false;
}else if(localName.equals(“PhonebookEntry”)){
this.in_innertag=false;
add(myParsedExampleDataSet);
}else if(localName.equals(“firstname”)){
this.in_firstname=false;
}else if(localName.equals(“lastname”)){
this.in_lastname=false;
}else if(localName.equals(“地址”)){
此.in_Address=false;
}
}
/**无法在以下结构上调用的获取:
*人物*/
@凌驾
公共无效字符(字符ch[],整数开始,整数长度){
如果(这个名字){
setfirstname(新字符串(ch,start,length));
}
如果(这个姓){
setlastname(新字符串(ch,start,length));
}
如果(此in_地址){
setAddress(新字符串(ch,start,length));
}
}
}

我在网上找到了一个XML教程,并对其进行了编辑,以使用您的XML文件。下面是代码。为了在我的机器上测试它,我已经从本地文件而不是在线文件中获取了XML文件,但这应该不太难实现

这将有望为您指明正确的方向

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();
          }
         }
}
package电话簿;
导入javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入java.io.File;
导入org.w3c.dom.Document;
导入org.w3c.dom.Element;
导入org.w3c.dom.Node;
导入org.w3c.dom.NodeList;
公共课程{
公共静态void main(字符串argv[]){
试一试{
File File=新文件(“phonebook.xml”);
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
文档doc=db.parse(文件);
doc.getDocumentElement().normalize();
System.out.println(“根元素”+doc.getDocumentElement().getNodeName());
NodeList nodeLst=doc.getElementsByTagName(“PhonebookEntry”);
System.out.println(“所有条目的信息”);
对于(int s=0;spublic 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);
}
}
/** 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);
    }