XML/JSON

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);
//{"num":1,"name":"xiaoming","info":"a good student"}
Gson g=new Gson();
Student stu2 = g.fromJson("{\"num\":1,\"name\":\"xiaoming\",\"info\":\"a good student\"}", Student.class);
System.out.println(stu2.getInfo());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值