/** *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; } }
Android XML解析之dom
最新推荐文章于 2021-05-26 22:30:06 发布