gpt4 book ai didi

java - Android:如何显示相同标签名称的所有 XML 值

转载 作者:行者123 更新时间:2023-11-30 09:49:18 24 4
gpt4 key购买 nike

我有 ff。来自 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>

我想显示两个 PhonebookEntry 值(名字、姓氏、地址)。目前,我的代码仅显示 John Smith 的 PhonebookEntry(最后一个条目)。这是我的代码。

解析XML.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);
}
}

ExampleHandler.java

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

ParsedExampleDataSet.java

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 开发的新手,非常感谢您的帮助! :)

最佳答案

其他回复已经指出,您需要一个列表来存储从 XML 中获取的所有 ParsedExampleDataSet 对象。

但我想提醒您注意有关 XML 处理程序的另一件事,它可能只会在以后(随机)对您产生影响。 characters 方法不是分配 XML 中标记之间找到的值的好地方,因为 characters 方法不能保证一次返回元素中的所有字符。可以在同一元素内多次调用它来报告到目前为止找到的字符。按照现在的实现方式,您最终会丢失数据并想知道发生了什么。

就是说,我会做的是使用 StringBuilder 来累积您的字符,然后在 endElement(...) 调用中分配它们。像这样:

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

然后您可以在您的 Activity 中检索 ParsedExampleDataSets 列表,并在多个 TextView 中显示或仅在一个 TextView 中显示。您的 Activity.onCreate(...) 方法可能如下所示:

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

关于java - Android:如何显示相同标签名称的所有 XML 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5865200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com