我正在尝试使用SAX解析器简单地进行xml解析。当我运行它时没有显示结果。我已将xml文件放入资源文件夹。但为什么它不起作用我无法理解。请帮助我。
MainActivity.java
package com.example.backgroud_ahsanul;
import java.io.InputStream;
import java.util.jar.Attributes;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=(TextView)findViewById(R.id.textView1);
try {
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser saxParser=factory.newSAXParser();
DefaultHandler handler=new DefaultHandler(){
boolean name=false;
boolean salary=false;
public void startElement(String uri, String localName,
String qName, org.xml.sax.Attributes attributes) throws org.xml.sax.SAXException {
if(qName.equalsIgnoreCase("name")){
name=true;
}
if(qName.equalsIgnoreCase("salary")){
salary=true;
}
}
public void endElement(String uri, String localName, String qName) throws org.xml.sax.SAXException {
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
if(name){
txt.setText(txt.getText()+"\n\n Name: "+new String(ch,start,length));
Toast.makeText(getApplicationContext(), "name", Toast.LENGTH_LONG).show();
name=false;
}
if(salary){
txt.setText(txt.getText()+"\n\n Salary: "+new String(ch,start,length));
Toast.makeText(getApplicationContext(), "salary", Toast.LENGTH_LONG).show();
salary=false;
}
}
};
InputStream is=getAssets().open("file.xml");
saxParser.parse(is, handler);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="76dp"
android:layout_marginTop="73dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
如果您想查看我的文档文件,您会看到以下链接: http://codepad.org/SAnFP1hr
答案 0 :(得分:0)
知道了! XML解析器在第一个标记之前讨厌空格。
打开file.xml并删除第一个标记之前的空格。
您提供的XML省略了这个以及它为什么适合我的原因!