Android:Sax 解析返回空值并检索同名标签中的值
我在 URL 上有这些 XML,
<?xml version="1.0" encoding="ISO-8859-1" ?>
<Phonebook>
<PhonebookEntry>
<firstname>John</firstname>
<lastname>Connor</lastname>
<Address>5,Downing Street</Address>
<Phone loc="home">9875674567</Phone>
<Phone loc="work">9875674567</Phone>
<Phone loc="mobile">78654562341</Phone>
</PhonebookEntry>
<PhonebookEntry>
<firstname>John</firstname>
<lastname>Smith</lastname>
<Address>6,Downing Street</Address>
<Phone loc="home">678-56-home</Phone>
<Phone loc="work">678-59-work</Phone>
<Phone loc="mobile">678-85-mobile</Phone>
</PhonebookEntry>
</Phonebook>
我能够提取名字、姓氏和地址的值,但是当涉及到电话标签时,我的代码返回空值。这是我的代码:
ParsingXML.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);
//System.setProperty("http.proxyHost"," 129.188.69.100 ");
//System.setProperty("http.proxyPort","1080");
//System.setProperty("http.nonProxyHosts","10.228.97.76");
/* 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 boolean in_Phone=false;
private boolean in_homePhone=false;
private boolean in_workPhone=false;
private boolean in_mobilePhone=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;
}else if (localName.equals("Phone")){
this.in_Phone=true;
String phoneattr=atts.getValue("loc");
if(phoneattr.equals("home")){
this.in_homePhone=true;
}else if(phoneattr.equals("work")){
this.in_workPhone=true;
}else if(phoneattr.equals("mobile")){
this.in_mobilePhone=true;
}
}
}
//else if (localName.equals("tagwithnumber")) {
// }
// Extract an Attribute
// String attrValue = atts.getValue("thenumber");
// int i = Integer.parseInt(attrValue);
// myParsedExampleDataSet.setExtractedInt(i);
// }
/** 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;
}else if(localName.equals("Phone")) {
this.in_Phone=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));
}
if(this.in_homePhone){
myParsedExampleDataSet.sethomePhone(new String(ch, start, length));
}
if(this.in_workPhone){
myParsedExampleDataSet.setworkPhone(new String(ch, start, length));
}
if(this.in_mobilePhone){
myParsedExampleDataSet.setmobilePhone(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;
private String Phone=null;
private String homephone=null;
private String workphone=null;
private String mobilephone=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;
}
//Phone
public String getPhone(){
return Phone;
}
public void sethomePhone(String homePhone){
this.homephone=homePhone;
}
public void setworkPhone(String homePhone){
this.homephone=homePhone;
}
public void setmobilePhone(String homePhone){
this.homephone=homePhone;
}
public String toString(){
return "firstname: " + this.firstname + "\n" + "lastname=: " + this.lastname + "\n" + "Address: " + this.Address+ "\n" + "homephone: " + this.homephone + "\n" + "workphone: " + this.workphone + "\n" + "mobilephone: " + this.mobilephone;
}
}
另外,如何检索 PhonebookEntry 标记中的两个值?
我对 java 和 android 开发有点陌生,非常感谢! :)
I have these XML on a URL
<?xml version="1.0" encoding="ISO-8859-1" ?>
<Phonebook>
<PhonebookEntry>
<firstname>John</firstname>
<lastname>Connor</lastname>
<Address>5,Downing Street</Address>
<Phone loc="home">9875674567</Phone>
<Phone loc="work">9875674567</Phone>
<Phone loc="mobile">78654562341</Phone>
</PhonebookEntry>
<PhonebookEntry>
<firstname>John</firstname>
<lastname>Smith</lastname>
<Address>6,Downing Street</Address>
<Phone loc="home">678-56-home</Phone>
<Phone loc="work">678-59-work</Phone>
<Phone loc="mobile">678-85-mobile</Phone>
</PhonebookEntry>
</Phonebook>
I was able to extract the values on firstname, lastname and Address, but when it comes to Phone tags, my code returns null values. Here are my code:
ParsingXML.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);
//System.setProperty("http.proxyHost"," 129.188.69.100 ");
//System.setProperty("http.proxyPort","1080");
//System.setProperty("http.nonProxyHosts","10.228.97.76");
/* 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 boolean in_Phone=false;
private boolean in_homePhone=false;
private boolean in_workPhone=false;
private boolean in_mobilePhone=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;
}else if (localName.equals("Phone")){
this.in_Phone=true;
String phoneattr=atts.getValue("loc");
if(phoneattr.equals("home")){
this.in_homePhone=true;
}else if(phoneattr.equals("work")){
this.in_workPhone=true;
}else if(phoneattr.equals("mobile")){
this.in_mobilePhone=true;
}
}
}
//else if (localName.equals("tagwithnumber")) {
// }
// Extract an Attribute
// String attrValue = atts.getValue("thenumber");
// int i = Integer.parseInt(attrValue);
// myParsedExampleDataSet.setExtractedInt(i);
// }
/** 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;
}else if(localName.equals("Phone")) {
this.in_Phone=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));
}
if(this.in_homePhone){
myParsedExampleDataSet.sethomePhone(new String(ch, start, length));
}
if(this.in_workPhone){
myParsedExampleDataSet.setworkPhone(new String(ch, start, length));
}
if(this.in_mobilePhone){
myParsedExampleDataSet.setmobilePhone(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;
private String Phone=null;
private String homephone=null;
private String workphone=null;
private String mobilephone=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;
}
//Phone
public String getPhone(){
return Phone;
}
public void sethomePhone(String homePhone){
this.homephone=homePhone;
}
public void setworkPhone(String homePhone){
this.homephone=homePhone;
}
public void setmobilePhone(String homePhone){
this.homephone=homePhone;
}
public String toString(){
return "firstname: " + this.firstname + "\n" + "lastname=: " + this.lastname + "\n" + "Address: " + this.Address+ "\n" + "homephone: " + this.homephone + "\n" + "workphone: " + this.workphone + "\n" + "mobilephone: " + this.mobilephone;
}
}
Another thing how can I retrieve both values in PhonebookEntry tags?
I'm kinda new to java and android dev, many thanks in advance! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此代码做出了错误的假设,即在标记的
startElement
和endElement
调用之间仅调用一次characters
方法。您不需要在
characters
方法中设置值的逻辑,而是需要在startElement
方法中初始化缓冲区,将字符收集到characters< 中的缓冲区中/code> 方法,然后在
endElement
方法中进行赋值并清除缓冲区。编辑:
实际上,您的代码中还存在一些其他问题...
您在模型类中设置了 homePhone 字段 setMobilePhone 和 setWorkPhone ...当您复制修改代码时,这是不可避免的风险。
并且您的处理程序仅创建一个结果,并且会覆盖并仅返回文件中的最后一个结果。
我已经尝试过,将一些方法更改为 Java 标准命名,并将一些 xml 更改为 CamelCase。
修订的 XML:
修订的 ParsedExampleDataSet:
以及执行解析的处理程序:
它在字段中放置了一些可能不需要的空格,但我怀疑您可以弄清楚如何修剪它。
调用它,您会得到一个列表而不是单个对象,但除了处理它之外,您的调用代码不应该改变太多。我没有尝试使用它,因为我没有在 Android 上做任何这些事情。
This code makes the incorrect assumption that the
characters
method will be called only once between thestartElement
andendElement
calls for a tag.Instead of having the logic for setting the values in the
characters
method, you need initialize a buffer in thestartElement
method, collect characters into the buffer in thecharacters
method, and then make the assignments and clear the buffer in theendElement
method.EDIT:
Actually, there were a few other issues in your code...
You had setMobilePhone and setWorkPhone in your model class setting the homePhone field... An inevitable risk when you copy-modify code.
And your handler was only creating one result, and would have overwritten and only returned the last one in the file.
I've played with it, changed some of the methods more to Java standard naming, and changed some of the xml to CamelCase as well.
Revised XML:
Revised ParsedExampleDataSet:
And the handler that does the parsing:
It puts some likely unwanted whitespace in the fields, but I suspect you can figure out how to trim that.
Calling it, you get a list rather than a single object, but other than dealing with that, your calling code shouldn't have to change too much. I didn't try to work with that, as I'm not doing any of this on android.
另外,要从元素获取属性,您可以使用如下内容:
您可以从 startElement 方法中的 atts 属性获取属性。
Also to get the attributes from an element you can use something like this:
You get the attributes from the atts Attributes in the startElement method.