public void test() throws Exception{ //读取xml文档 SAXReader reader = new SAXReader(); Document doc = reader.read(new File("./src/contacts.xml")); //读取根标签 Element rootELem = doc.getRootElement(); StringBuffer sb = new StringBuffer(); getChildNodes(rootELem,sb); System.out.println(sb.toString()); } /** * 获取当前标签的所有子标签 */ private void getChildNodes(Element elem,StringBuffer sb){ //System.out.println(elem.getName()); //开始标签 sb.append("<"+elem.getName()); //得到标签的属性列表 List<Attribute> attrs = elem.attributes(); if(attrs!=null){ for (Attribute attr : attrs) { //System.out.println(attr.getName()+"="+attr.getValue()); sb.append(" "+attr.getName()+"=\""+attr.getValue()+"\""); } } sb.append(">"); //得到文本 //String content = elem.getText(); Iterator<Node> it = elem.nodeIterator(); while(it.hasNext()){ Node node = it.next(); //标签 if(node instanceof Element){ Element el = (Element)node; getChildNodes(el,sb); } //文本 if(node instanceof Text){ Text text = (Text)node; sb.append(text.getText()); } //结束标签 sb.append("</"+elem.getName()+">");
}
XML
<?xml version="1.0" encoding="gbk"?><contactList> <contact id="001"> <name>张三</name> <age>20</age> <phone>1216461316</phone> <email>zhangsan@qq.con</email> <qq>2451356331</qq> </contact> <contact id="002"> <name>李四</name> <age>23</age> <phone>122341316</phone> <email>lisi@qq.con</email> <qq>23424331</qq> <app>101010</app> </contact> <abc></abc> </contactList>腾不出时间思考的人,迟早会腾出时间来后悔;腾不出时间学习的人,迟早会腾出时间来伤悲。