xml读取完整的xml文件(1)

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>
腾不出时间思考的人,迟早会腾出时间来后悔;腾不出时间学习的人,迟早会腾出时间来伤悲。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值