日期:2014-05-20 浏览次数:20812 次
package com.ss; import java.io.IOException; import java.net.URL; import java.util.List; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; public class ParseXml { public static void main(String[] args) { SAXBuilder builder = new SAXBuilder(false); String xml="user.xml";//这个路径表示跟当前类在同一个package下 URL url = ParseXml.class.getResource(xml); Document doc; try { doc = builder.build(url); Element dataset = doc.getRootElement(); List userList = dataset.getChildren(); for(int i=0;i<userList.size();i++) { Element user = (Element)userList.get(i); Element userName =(Element)user.getChildren().get(0); Element password =(Element)user.getChildren().get(1); System.out.println("username:" +userName.getText() +" password:"+password.getText()); } } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
------解决方案--------------------
public static void readxmlFile() { String fileName = "etc/abc.xml"; Element element = null; File f = new File(fileName); DocumentBuilder db = null; DocumentBuilderFactory dbf = null; try { dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); Document dt = db.parse(f); element = dt.getDocumentElement(); NodeList childNodes = element.getChildNodes(); String userName = ""; String password = ""; for (int i = 0; i < childNodes.getLength(); i++) { Node node1 = childNodes.item(i); if ("user".equals(node1.getNodeName())) { NodeList nodeDetail = node1.getChildNodes(); for (int j = 0; j < nodeDetail.getLength(); j++) { // 遍历<users>下的节点 Node detail = nodeDetail.item(j); // 获得<users>元素每一个节点 if ("username".equals(detail.getNodeName())) userName = detail.getTextContent(); else if ("password".equals(detail.getNodeName())) { password = detail.getTextContent(); } } System.out.println("userName:" + userName + " password:" + password); } } } catch (Exception e) { e.printStackTrace(); } }
------解决方案--------------------
可以直接使用java自带的DOM解析方式
------解决方案--------------------
dom4j xpath解析很方便
------解决方案--------------------
dom4j