XML是一种通用的数据交换格式,基本解析方式有SAX和DOM。SAX是基于事件流的解析,DOM是基于XML文档树结构的解析。
DOM解析器读入整个文档,挼后构建一个驻留内存的树结构,软后代码就可以使用DOM接口来操作这个树结构。优点:整个文档树在内存中,便于操作,支持删除,修改等操作;缺点:将整个文档调入内存,让费时间和空间;使用场合:一旦解析了文档还需要多次访问这些数据,硬件资源充足。
SAX解析器通过事件驱动。当解析器发现元素开始,元素结束,文本,文档的开始或结束等时,发送事件,程序员编写响应这些事件的代码,保存数据。优点:不用事先调入文档,占用资源少;缺点:不是持久的,事件过后若没保存数据,数据就丢了;无状态性;从事件中只能得到文本,不知道文本属于哪个元素。使用场合:只需要xml文档很少内容,很少回头访问,机器内存少。
SAX解析实例:
//生成xml字符串
private String toXML(){
StringBuffer s=new StringBuffer();
s.append("<?xml version='1.1' encoding='utf-8'?>");
s.append("<Student><name>孤狼</name>");
s.append("<age>20</age>");
s.append("<sex>men</sex></Student>");
return s.toString();
}
//解析XML方法
private void parserXML(String xml){
SAXParserFactory spf=SAXParserFactory.newInstance();
SAXParser sp;
try {
sp = spf.newSAXParser();
StudentPresertHandler sph=new StudentPresertHandler();
sp.parse(new ByteArrayInputStream(xml.getBytes()),sph);
Student stu=sph.getStudent();
} catch (Exception e) {
e.printStackTrace();
}
}
//解析XML具体实现类
public class StudentPresertHandler extends DefaultHandler {
boolean name,age,sex;
Student s=new Student();
//读取文本
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
String str=new String(ch).substring(start, length+start);
if(name)
s.setName(str);
else if(age)
s.setAge(Integer.parseInt(str));
else if(sex)
s.setSex(str);
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
//读取标签对结束标签
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if(localName.equals("name"))
name=false;
if(localName.equals("age"))
age=false;
if(localName.equals("sex"))
sex=false;
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
Student student=new Student();
}
//读取标签对开始标签
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(localName.equals("name"))
name=true;
else if(localName.equals("age"))
age=true;
else if(localName.equals("sex"))
sex=true;
}
public Student getStudent(){
return s;
}
}
JSON是存储和转换文本信息的语法,类似XML。
JSON比XML更小,更快,更容易解析。
//JSON格式,{}为对象,[]为数组
{
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
}
JSON实例:
//将student对象转换成Json格式字符串(需要架包) 也可以通过标准格式进行转换
private String toJson(){
Student student=new Student();
student.setName("方兵");
student.setAge(18);
student.setSex("man");
JSONObject js=new JSONObject();
return js.fromObject(student).toString();
}
//解析Json
private void parserJSON(String body){
JSONTokener jsonparser=new JSONTokener(body);
JSONObject js;
try {
js = (JSONObject) jsonparser.nextValue();
Student student=new Student();
student.setName(js.getString("name"));
student.setAge(Integer.parseInt(js.getString("age")));
student.setSex(js.getString("sex"));
System.out.println("name="+student.getName()+"age="+student.getAge( )+"sex="+student.getSex());
} catch (Exception e) {
e.printStackTrace();
}
}