在XML文件中由于更多的是描述信息的内容,所以在得到一个XML文档后应该利用程序按照其中元素的定义名称取出对应的内容,这样的操作就称为XML解析。
在XML解析中,W3C定义了SAX和DOM两种解析方式。
DOM树解析所提供的随机访问方式给应用程序开发带来很大的灵活性,它可以任意地控制整个XML文档的内容,然而由于DOM分析器把整个XML文档转化成DOM树放在了内存中,因此,当文档较大或者结果较复杂时,对内存的需求较高。综上,DOM分析器对机器性能的要求比较高,程序的效率并不是十分理想。但是DOM所采用的树结构的思想与XML文档的结果相吻合,同时随机访问带来的方便,所以DOM分析器还是有很广泛的使用价值。
以下面 book.xml为例说明:客户端访问服务器端的book.xml,并解析。
book.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="8">
<name>Economics Event</name>
<price>88.5</price>
</book>
<book id="9">
<name>The World Is Flat</name>
<price>69.0</price>
</book>
</books>
目录结构: 客户端 (左边 ) 服务器端(右边)
客户端:Book.java
package com.dom.data;
public class Book {
private int id;
private String name;
private float price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
客户端 DomService.java
package com.dom.data;
public class Book {
private int id;
private String name;
private float price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
客户端: HttpUtis.java
package com.dom.http;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUtils {
public static InputStream getXML(String path) {
InputStream inputStream = null;
try {
URL url = new URL(path);
if (url != null) {
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoInput(true); // 从服务器获取数据
httpURLConnection.setRequestMethod("GET");
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {
inputStream = httpURLConnection.getInputStream();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inputStream;
}
}
程序运行结果:
Book [id=12, name=thinking in java, price=85.5]
Book [id=13, name=spring in action, price=39.0]
参考文章:
http://www.iteye.com/topic/400602 (此文内有详细的xml内各个节点元素的类型:Document,Element,Text,Attribute,Comment等等)
原文:http://blog.csdn.net/neu_yousei/article/details/22853847