XML解析
获取文档内容
FileInputStream fis = new FileInputStream ( "F://Demo.xml" ) ;
SAXReader sa = new SAXReader ( ) ;
Document read = sa. read ( fis) ;
Element root = read. getRootElement ( ) ;
Element s = root. element ( "book" ) ;
String book = s. elementText ( "name" ) ;
System . out. println ( book) ;
读取网页内容
String phone = "19756548052" ;
URL u = new URL ( "http://apis.juhe.cn/mobile/get?phone=" + phone + "&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253" ) ;
URLConnection conn = u. openConnection ( ) ;
InputStream is = conn. getInputStream ( ) ;
SAXReader sa = new SAXReader ( ) ;
Document docu = sa. read ( is) ;
Element rool = docu. getRootElement ( ) ;
String s = rool. elementText ( "resultcode" ) ;
System . out. println ( s) ;
生成XML文件
Document doc = DocumentHelper . createDocument ( ) ;
Element books = doc. addElement ( "books" ) ;
Element book = books. addElement ( "book" ) ;
Element name = books. addElement ( "name" ) ;
Element text = name. addText ( "哈哈哈" ) ;
FileOutputStream fos= new FileOutputStream ( "F://demo1.xml" ) ;
XMLWriter xm= new XMLWriter ( fos) ;
xm. write ( doc) ;
xm. close ( ) ;
JSON
package json ;
public class Student {
private int num;
private String name;
private String info;
@Override
public String toString ( ) {
return "Student{" +
"num=" + num +
", name='" + name + '\'' +
", info='" + info + '\'' +
'}' ;
}
public int getNum ( ) {
return num;
}
public void setNum ( int num) {
this . num = num;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public String getInfo ( ) {
return info;
}
public void setInfo ( String info) {
this . info = info;
}
public Student ( int num, String name, String info) {
this . num = num;
this . name = name;
this . info = info;
}
public Student ( ) {
}
}
Student stu = new Student ( 1 , "xiaoming" , "a good student" ) ;
String s = new Gson ( ) . toJson ( stu) ;
System . out. println ( s) ;
Gson g= new Gson ( ) ;
Student stu2 = g. fromJson ( "{\"num\":1,\"name\":\"xiaoming\",\"info\":\"a good student\"}" , Student . class ) ;
System . out. println ( stu2. getInfo ( ) ) ;