xml的操作-解析篇
2014-05-04 11:16 吴文付 工作上,学习上,肯定会碰到xml的操作。这里提供详细的xml解析方法。
这里的规划如下:简单的布局3个按钮。3个按钮,对应3种解析xml的方法。分别为 sax解析 dom解析 pull解析
12:56 完成了dom的解析。比较简单。
后来增加了dom4j的解析。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version='1.0' encoding='utf-8' standalone='yes' ?><beauties><beauty><name>杨幂</name><age>23</age></beauty><beauty><name>林志玲</name><age>28</age></beauty></beauties>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private List<Beauty> getBeauties(InputStream inStream) throws Throwable { List<Beauty> beauties = new ArrayList<Beauty>(); // DOM文件创建工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // DOM创建对象 DocumentBuilder builder = factory.newDocumentBuilder(); // 获取XML的DOM Document document = builder.parse(inStream); // 获取XML文件的内容 Element root = document.getDocumentElement(); // 获取XML文件的节点 NodeList beautyNode = root.getElementsByTagName("beauty"); for (int i = 0; i < beautyNode.getLength(); i++) { Beauty Beauty = new Beauty(); Element beautyElemt = (Element) beautyNode.item(i); // 获取当前节点的字节点 NodeList beautyChildNode = beautyElemt.getChildNodes(); for (int y = 0; y < beautyChildNode.getLength(); y++) { if (beautyChildNode.item(y).getNodeType() == Node.ELEMENT_NODE) { Element childElent = (Element) beautyChildNode.item(y); if ("name".equals(childElent.getNodeName())) { Beauty.setName(childElent.getFirstChild() .getNodeValue()); } else if ("age".equals(childElent.getNodeName())) { Beauty.setAge(new Short(childElent.getFirstChild() .getNodeValue())); } } } beauties.add(Beauty); } return beauties; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private List<Beauty> dom4jXMLResolve(InputStream inStream) { List<Beauty> beautiesList = null; Beauty beauty = new Beauty(); InputStream is = inStream; try { SAXReader reader = new SAXReader(); org.dom4j.Document doc = reader.read(is); org.dom4j.Element eleRoot = doc.getRootElement(); // 获得root根节点,引用类为 // org.dom4j.Element System.out.println("----->根节点" + eleRoot.getName()); beautiesList = new ArrayList<Beauty>(); // 获取root子节点,即beauty Iterator<org.dom4j.Element> iter = eleRoot.elementIterator(); // while (iter.hasNext()) { org.dom4j.Element eleBeauty = (org.dom4j.Element) iter.next(); // 筛选节点 if ("beauty".equals(eleBeauty.getName())) { // 获取beauty子节点,即name、age Iterator<org.dom4j.Element> innerIter = eleBeauty .elementIterator(); beauty = new Beauty(); while(innerIter.hasNext()) { org.dom4j.Element ele = (org.dom4j.Element) innerIter .next(); if ("name".equals(ele.getName())) { String name = ele.getText(); beauty.setName(name); } if ("age".equals(ele.getName())) { String age = ele.getText(); beauty.setAge(Short.parseShort(age)); } } } beautiesList.add(beauty); // 添加到集合中 } } catch (DocumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return beautiesList; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private List<Beauty> saxResolveXML(InputStream in){ InputStream is = in; List<Beauty> beautiesList = new ArrayList<Beauty>(); try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); BeautyHandler handler = new BeautyHandler(); // person处理Handler saxParser.parse(is, handler); // handler解析xml // 获取解析的xml //String xmlHeader = handler.getXMLHeader(); beautiesList = handler.getBeauties(); } catch (FactoryConfigurationError e) { // SAXParserFactory.newInstance e.printStackTrace(); } catch (ParserConfigurationException e) { // factory.newSAXParser e.printStackTrace(); } catch (SAXException e) { // factory.newSAXParser e.printStackTrace(); } catch (IllegalArgumentException e) { // saxParser.parse e.printStackTrace(); } catch (IOException e) { // saxParser.parse e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return beautiesList; } /** Handler处理类 */ private final class BeautyHandler extends DefaultHandler{ private List<Beauty> beautiesList = null; // 保存beauty private Beauty beauty = null; private String tag = null; // xml Element /** 返回解析的Beauty实例数组 */ public List<Beauty> getBeauties(){ return beautiesList; } @Override public void startDocument() throws SAXException{ super.startDocument(); beautiesList = new ArrayList<Beauty>(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{ super.startElement(uri, localName, qName, attributes); if("root".equals(localName)) { String attrAuthor = attributes.getValue(0); String attrDate = attributes.getValue(1); } else if("beauty".equals(localName)) { beauty = new Beauty(); } tag = localName; } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); if (null != tag) { String value = new String(ch, start, length); System.out.println("value = " + value); if ("name".equals(tag)) { beauty.setName(value); } else if ("age".equals(tag)) { beauty.setAge(new Short(value)); } } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if("beauty".equals(qName)) { beautiesList.add(beauty); beauty = null; } tag = null; super.endElement(uri, localName, qName); } @Override public void endDocument() throws SAXException{ // personsList = null; super.endDocument(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private static List<Beauty> pullXMLResolve(InputStream inputStream) throws Exception{ List<Beauty> beautiesList = null; Beauty beauty = null; XmlPullParser parser = Xml.newPullParser(); parser.setInput(inputStream, "UTF-8"); int event = parser.getEventType();//产生第一个事件 while(event!=XmlPullParser.END_DOCUMENT){ switch(event){ case XmlPullParser.START_DOCUMENT://判断当前事件是否是文档开始事件 beautiesList = new ArrayList<Beauty>();//初始化集合 break; case XmlPullParser.START_TAG://判断当前事件是否是标签元素开始事件 if("beauty".equals(parser.getName())){//判断开始标签元素是否是beauty beauty = new Beauty(); } if(beauty!=null){ if("name".equals(parser.getName())){//判断开始标签元素是否是name beauty.setName(parser.nextText()); }else if("age".equals(parser.getName())){//判断开始标签元素是否是age beauty.setAge(Short.parseShort(parser.nextText())); } } break; case XmlPullParser.END_TAG://判断当前事件是否是标签元素结束事件 if("beauty".equals(parser.getName())){//判断结束标签元素是否是beauty beautiesList.add(beauty);//将beauty添加到beautiesList集合 beauty = null; } break; } event = parser.next();//进入下一个元素并触发相应事件 }//end while return beautiesList; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Beauty { String name; Short age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Short getAge() { return age; } public void setAge(Short age) { this.age = age; } @Override public String toString() { return "Beauty [age=" + age + ", name=" + name + "]"; } public Beauty(String name, Short age) { this.name = name; this.age = age; } public Beauty() { } }
演示的工程地址如下:所需要的jar包在工程的libs中
http://download.csdn.net/detail/douniwan123654/7293451
效果图:
解析后的效果
QQ:540045865
热爱生活,热爱编程。