Android XML解析之dom

/**
*param inputSteam xml_inputStream
*
*/
public List<Book> getBooks(InputStream inputStream) throws Exception {
		List<Book> list = new ArrayList<Book>();
		// 创建一个document解析的工厂
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(inputStream);
		Element element = document.getDocumentElement();// 获得稳定的元素节点
		NodeList bookNodes = element.getElementsByTagName("book");
		for (int i = 0; i < bookNodes.getLength(); i++) {
			Element bookeElement = (Element) bookNodes.item(i);
			Book book = new Book();
		//	book.setId(Integer.parseInt(bookeElement.getAttribute("id")));
			NodeList childNodes = bookeElement.getChildNodes();
			for (int j = 0; j < childNodes.getLength(); j++) {
				if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
					
					if ("name".equals(childNodes.item(j).getNodeName())) {
						book.setName(childNodes.item(j).getFirstChild()
								.getNodeValue());
					} 
					if ("price".equals(childNodes.item(j).getNodeName())) {
						book.setPrice(Float.parseFloat(childNodes.item(j)
								.getFirstChild().getNodeValue()));
					}
					if ("id".equals(childNodes.item(j).getNodeName())) {
						book.setId(Integer.parseInt(childNodes.item(j).getFirstChild()
								.getNodeValue()));
					}
				}
			}
			list.add(book);
		}
		return list;
}

//Book.java



public class Book {


	private int id;
	private String name;
	private float price;
	
	
	public float 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 Book() {
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
	}


	
}

//httpUtil.java
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);
			if (url != null) {
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.setConnectTimeout(3000);
				connection.setDoInput(true);
				connection.setRequestMethod("GET");
				int code = connection.getResponseCode();
				if (code == 200) {
					inputStream = connection.getInputStream();
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return inputStream;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值