使用dom解析xml文件

老罗视频学习笔记。


前边有两种解析xml的方式,sax,和pull,都比较适用于android端解析。接下来的dom方式是把xml文件当做树状结构来解析,类似于之前用的c++中解析方式,c++中用过的是tinyxml.lib和libcurl.dll。

一.客户端。

和前两个例子一样,还用同一个服务器,同一个xml文件。

1)定义一个person类,用来存储person的数据,并且提供接口供外界来操作。和pull例子里的一样,拷贝即可。

person.java

public class person {

	public person() {
		// TODO Auto-generated constructor stub
	}
	//成员变量
	private String name = null;
	private int id = 0;
	private int age = 0;
	//有参构造函数
	public person(String name, int id, int age) {
		super();
		this.name = name;
		this.id = id;
		this.age = age;
	}

	//get函数
	public String getName() {
		return name;
	}
	//set函数
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	//toString()函数
	@Override
	public String toString() {
		return "person [name=" + name + ", id=" + id + ", age=" + age + "]";
	}
	
	
}

2)HttpUtils类,定义了以http的GET方式从服务器端获取IO数据流。和sax,还有pull中定义的一样,拷贝即可。

public class HttpUtils {

	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}

public static InputStream getXML(String path) {
		
		
		InputStream inputStream = null;
		try {
			URL url = new URL(path);
			
			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 (Exception e) {
			// TODO: handle exception
		}
		
		return inputStream;
	}
	
	
	
}


3)关键的是domService类,这里边具体实现了dom方式解析返回的inputStream流,并且存入list中,list中是person对象。

public class domService {

	public domService() {
		// TODO Auto-generated constructor stub
	}

	
	public static List<person> getPersons(InputStream inputStream) {
		List<person>list = new ArrayList<person>();
		//创建一个document解析的工厂
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			//这个document就是整个文档
			Document document = builder.parse(inputStream);
			//获得文件的元素节点
			org.w3c.dom.Element element =  document.getDocumentElement();
			NodeList personNodes = ( element).getElementsByTagName("person");
			int count = personNodes.getLength();
			System.out.print(count);
			for(int i = 0;i<personNodes.getLength();i++){
				//此处的Element一定要使用org.w3c.dom包下的,不要用错
				org.w3c.dom.Element personElement = (org.w3c.dom.Element) personNodes.item(i);
				person personPerson = new person();
				System.out.print("!!!\n");
				personPerson.setId(Integer.parseInt(personElement.getAttribute("id")));
				System.out.print("!!!\n");
				NodeList childnNodeList = (personElement).getChildNodes();
				int countj = childnNodeList.getLength();
				System.out.print(countj);
				for(int j = 0;j<childnNodeList.getLength();j++){
					if(childnNodeList.item(j).getNodeType()==Node.ELEMENT_NODE){
						if("name".equals(childnNodeList.item(j).getNodeName())){
							personPerson.setName(childnNodeList.item(j).getFirstChild().getNodeValue());
						}else if ("age".equals(childnNodeList.item(j).getNodeName())) {
							personPerson.setAge(Integer.parseInt(childnNodeList.item(j).getFirstChild().getNodeValue()));
						}
					}
				}
				list.add(personPerson);
			}
			return list;
		} 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();
		}
		
		return list;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String pathString = "http://localhost:8080/myhttp/person.xml";
		//从服务器中获取InputStream流
		InputStream  inputStream = HttpUtils.getXML(pathString);
		domService domSer = new domService();
		try {
			//把获取到的inputstream流存入list中
			List<person> list = domSer.getPersons(inputStream);
			//循环输出
			for(person person : list) {
				System.out.println(person.toString());
			}
		
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}


导包一定不能导错,刚开始没在意,导致解析不报错,但是就是解析不出来。


4)测试类,这里测试就不专门写一个类了,在3)中HttpUtils中定义一下main函数 ,即可测试了。

二.服务器端和之前的一样样的。

结果也和之前的一样一样的。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值