您的位置:首页 > Web前端 > JavaScript

XML解析、DOM解析、SAX解析、Json解析

2015-08-11 22:10 721 查看
Url查看api url
读取内容为图片时使用字节流的读取方法示例

读取网站源代码时可以用字符读取方式示例

枚举

xml解析
DOM解析
对dom中节点的解释

解析整个文档导入包都是dom的附加解释

解析其中的一部分

SAX解析

Json解析
生成JSON类型的数据

解析JSON数据

读取一个文件中的JSON数据然后用上面的读取方法读取

其实这篇文章很早就写了,但是一直放在草稿箱里忘了发表,直到今天整理草稿箱的时候才发现了它。



Url(查看api url)

读取内容为图片时使用字节流的读取方法,示例:

try {
URL url2=new URL("http://e.hiphotos.baidu.com/image/h%3D200/sign=4b8869d4a9345982da8ae2923cf5310b/d009b3de9c82d15810eaa411840a19d8bc3e4222.jpg");
File fileImage=new File("d://a.jpg");
if(!fileImage.exists()){//判断文件是否存在
fileImage.createNewFile();//不存在则创建新文件
}
InputStream is= url2.openStream();//获取输入流
byte[] array=new byte[1024];
int i=is.read(array);//以字节方式进行读取
OutputStream os=new FileOutputStream(fileImage);//创建输出流
while(i!=-1){
os.write(array, 0, array.length);
i=is.read(array);
}
os.flush();//写入时注意最后的刷新
os.close();
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


读取网站源代码时可以用字符读取方式,示例:

try {
URL url=new URL("http://www.baidu.com");
InputStream is=url.openStream();//获取输入流
BufferedReader br=new BufferedReader(new InputStreamReader(is));//将输入流转化成带缓冲字符输入流
String str=br.readLine();//直接读取某一行
while(str!=null){
System.out.println(str);
str=br.readLine();
}
br.close();
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


枚举

默认赋int类型的值

public enum Sex {
MALE,FEMALE;
}
"******************************************************"
public class Student {
private String name;
private Sex sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Sex getSex() {
return sex;
}
public void setSex(Sex sex) {
this.sex = sex;
}
}
"******************************************************"
public class Main {

public static void main(String[] args) {
Student zhangsan=new Student();
zhangsan.setSex(Sex.MALE);
switch(zhangsan.getSex()){
case MALE:
break;
case FEMALE:
break;
}

}

}


xml解析

<? xml version="1.0" encoding="UTF-8">


DOM解析

创建解析器工厂对象

由解析器工厂对象创建解析器对象

由解析器对象指定XML文件进行解析,构建相应DOM树,创建Document对象

以Document对象为起点对DOM树的节点进行增删改查操作。

对dom中节点的解释

<html>
<head>
<title>DOM 教程</title>
</head>
<body>
<h1>DOM 第一课</h1>
<p>Hello world!</p>
</body>
</html>
从上面的 HTML 中:
<html> 节点没有父节点;它是根节点
<head> 和 <body> 的父节点是 <html> 节点
文本节点 "Hello world!" 的父节点是 <p> 节点
并且:
<html> 节点拥有两个子节点:<head> 和 <body>
<head> 节点拥有一个子节点:<title> 节点
<title> 节点也拥有一个子节点:文本节点 "DOM 教程"
<h1> 和 <p> 节点是同胞节点,同时也是 <body> 的子节点
并且:
<head> 元素是 <html> 元素的首个子节点
<body> 元素是 <html> 元素的最后一个子节点
<h1> 元素是 <body> 元素的首个子节点
<p> 元素是 <body> 元素的最后一个子节点


解析整个文档(导入包都是dom的,附加解释)

>

<Profiles>
<Weather>
<city>
北京
</city>


DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
try {
// 使用解析器工厂创建解析器
DocumentBuilder bulider=dbf.newDocumentBuilder();
//  使用解析器解析文档生成倒挂树document
Document doc=bulider.parse("d:\\11.txt");
// 得到文档中所有weather标签
NodeList list=doc.getElementsByTagName("Weather");
//得到第一个weather
Node node=list.item(0);
// 得到weather标签的第一个子标签city
Node child=node.getFirstChild();
// 得到city的下一个标签,同在Weather下的同胞类
Node next=child.getNextSibling();
while(next != null){
//注意为ELEMENT_NODE,判断节点是否为标签形式
if(next.getNodeType() == Node.ELEMENT_NODE){
"//得到节点的下一节点,好比city---北京",//北京是city的一个子节点
Node content=next.getFirstChild();
// 得到该子节点的第一个子标签不能为空
if(content!=null){
//得到子节点内含的值 System.out.println(next.getFirstChild().getNodeValue());
}
}
next=next.getNextSibling();
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


解析其中的一部分

try {
DocumentBuilder bulider=dbf.newDocumentBuilder();
Document doc=bulider.parse("d://11.txt");
NodeList list=doc.getElementsByTagName("city");
for(int i=0;i<list.getLength();i++){
Node node=list.item(i);
System.out.println(node.getFirstChild().getNodeValue().trim());

}
NodeList list2=doc.getElementsByTagName("status1");
String weather=list2.item(0).getFirstChild().getNodeValue();
System.out.println(weather);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


所用的11.txt

<?xml version="1.0" encoding="UTF-8"?>
<!-- published at 2015-08-03 15:41:42 -->
<Profiles>
<Weather>
<city>
北京
</city>
<city>上海</city>
<city>广州</city>
<city>深圳</city>
<city>天津</city>
<status1>阴</status1>
<status2>多云</status2>
<figure1>yin</figure1>
<figure2>duoyun</figure2>
<direction1>无持续风向</direction1>
<direction2>无持续风向</direction2>
<power1>≤3</power1>
<power2>≤3</power2>
<temperature1>30</temperature1>
<temperature2>23</temperature2>
<ssd>7</ssd>
<tgd1>27</tgd1>
<tgd2>27</tgd2>
<zwx>1</zwx>
<ktk>3</ktk>
<pollution>3</pollution>
<xcz>4</xcz>
<zho></zho>
<diy></diy>
<fas></fas>
<chy>1</chy>
<zho_shuoming>暂无</zho_shuoming>
<diy_shuoming>暂无</diy_shuoming>
<fas_shuoming>暂无</fas_shuoming>
<chy_shuoming>短袖衫、短裙、短裤、薄型T恤衫、敞领短袖
.
..............衫</chy_shuoming>
<pollution_l>轻度</pollution_l>
<zwx_l>最弱</zwx_l>
<ssd_l>偏热</ssd_l>
<fas_l>暂无</fas_l>
<zho_l>暂无</zho_l>
<chy_l>薄短袖类</chy_l>
<ktk_l>较适宜开启(制冷)</ktk_l>
<xcz_l>不太适宜</xcz_l>
<diy_l>暂无</diy_l>
<pollution_s>对空气污染物扩散无明显影响</pollution_s>
<zwx_s>紫外线最弱</zwx_s>
<ssd_s>天气偏热,适当调整穿衣后,仍可达到比较舒适的程度。</ssd_s>
<ktk_s>比较适宜开启空调</ktk_s>
<xcz_s>洗车后未来1-2天内有降水、大风或沙尘天气,不太适宜洗车</xcz_s>
<gm>1</gm>
<gm_l>低发期</gm_l>
<gm_s>环境温度较高,要提防长时间在空调环境中引发的空调病;</gm_s>
<yd>5</yd>
<yd_l>不适宜</yd_l>
<yd_s>天气炎热,不适宜户外运动;</yd_s>
<savedate_weather>2015-08-03</savedate_weather>
<savedate_life>2015-08-03</savedate_life>
<savedate_zhishu>2015-08-03</savedate_zhishu>
<udatetime>2015-08-03 08:21:36</udatetime>
</Weather>
</Profiles>


SAX解析

SAXParserHandler类

解释如何捕获和响应各个事件

1. startDocument( )和endDocument( )事件是在文档的起始处和结束处被激发的

2. startElement( )和 endElement( )事件是在遇到起始标记和结束结束标记时被激发的

3. characters( )事件是在遇到字符数据时被激发的

创建SAXParserFactory的实例

创建SAXParser的实例

创建SAXParserHandler的类

使用parse()方法来解析XML文档

"***********************继承defaultHandler***********************"
public class Sax extends DefaultHandler {

@Override
public void characters(char[] ch, int start, int length) throws SAXException {

super.characters(ch, start, length);
System.out.println(new String(ch,start,length));

}

@Override
public void endDocument() throws SAXException {

super.endDocument();
System.out.println("这是文档结束");
}

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {

super.endElement(uri, localName, qName);
System.out.println("这是标签结束");
}

@Override
public void startDocument() throws SAXException {

super.startDocument();
System.out.println("这是文档开始");
}

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

super.startElement(uri, localName, qName, attributes);
System.out.println("标签开始"+qName);
}

}
"*********************实现方法**************************"
public class Test {
public static void main(String[] args) {
SAXParserFactory spf=SAXParserFactory.newInstance();
try {
SAXParser sp=spf.newSAXParser();
Sax sax=new Sax();
sp.parse("d:\\11.txt", sax);
} catch (ParserConfigurationException | SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


Json解析

{代表一个类}—-[代表数组]—–key : value

导入外部的jar包

Builderpath—configure Builder—library—addExternal—包名

生成JSON类型的数据

private static String creatJSON(){
//相当于先建一个{   }
JSONObject obj=new JSONObject();
//"city":"北京",放入格式
obj.put("city","北京");
obj.put("cityid","123");
JSONObject today=new JSONObject();
today.put("date","2015-08-03");
today.put("week","星期一");
//创建数组[{"name":"感冒"},{"name":"防晒"},{"name":"炎热"}]
JSONArray array=new JSONArray();
JSONObject index1=new JSONObject();
//放入单个,相当于 key : value
index1.put("name", "感冒");
JSONObject index2=new JSONObject();
index2.put("name", "防晒");
JSONObject index3=new JSONObject();
index3.put("name", "炎热");
array.add(index1);
array.add(index2);
array.add(index3);
//最后都加入
today.put("index", array);
obj.put("today", today);
//以字符串形式输出
System.out.println(obj.toString());
return obj.toString();
}
//最后输出
{"city":"北京","cityid":"123","today":{"date":"2015-08-03","week":"星期一","index":[{"name":"感冒"},{"name":"防晒"},{"name":"炎热"}]}}


解析JSON数据

public static void main(String[] args) {
String json=creatJSON();
//创建JSON对象,传入json数据
JSONObject obj=JSONObject.fromObject(json);
//得到key为"city"的对象的值
System.out.println(obj.getString("city"));
//因为today也为对象,所以用JSONObject today创建
JSONObject today=obj.getJSONObject("today");
//创建json数组
JSONArray array=today.getJSONArray("index");
for (int i = 0; i < array.size(); i++) {
JSONObject obj1=array.getJSONObject(i);
System.out.println(obj1.getString("name"));
"*******obj1.getString("name")的到key对应的value值**********"
}
}


读取一个文件中的JSON数据,然后用上面的读取方法读取。

File file=new File("d:\\22.txt");
String json="";
try{
BufferedReader br=new BufferedReader(new FileReader(file));
String line=br.readLine();
while(line!=null){
json+=line;
line=br.readLine();
}
br.close();
System.out.println(json);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  xml url dom json