- /*****
- * 解析xml文件
- * @param filename 要解析的xml文件
- */
- private void parsesXML(String filename){
- try {
- //通过 SAXBuilder 对象去 解析一个 xml 文件,获取 Document 对象
- SAXBuilder saxBuilder = new SAXBuilder();
- //获取到的 Document 对象中封装了所有xml文档内容
- InputStream in = getClass().getResourceAsStream(filename);
- Document document = saxBuilder.build(in);
- //得到根节点
- Element root = document.getRootElement(); //DataSource
- System.out.println("root:"+root.getName());
- //得到根节点下面的所有子节点
- List<Element> children = root.getChildren(); //param
- //循环遍历所有子节点
- for (Element element : children) {
- //获取属性
- List<Attribute> attributes = element.getAttributes(); //database version
- for (Attribute attribute : attributes) {
- System.out.println(attribute.getName()+":"+attribute.getValue());
- }
- //获得属性下面的 ‘集合’ <driver> <url> <users> <password>
- List<Element> childs = element.getChildren();
- for (Element child : childs) {
- System.out.println(child.getName()+":"+child.getValue());
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/150720134599.html
来源: http://www.codesnippet.cn/detail/150720134599.html