小说网站 搜小说 无限网 烟雨红尘 小说爱好者 免费小说 免费小说网站

java Domj4读取xml文件加强训练案例

需求:给出一段xml文件。要求按照鸳鸯输出。

xml文件代码如下:

<?xml version="1.0" encoding="utf-8"?>
<contactList>
	<contact id="001">
		<name>张三</name>
		<age>20</age>
		<phone>134222223333</phone>
		<email>zhangsan@qq.com</email>
		<qq>432221111</qq>
	</contact>
	<contact id="002">
		<name>李四</name>
		<age>20</age>
		<phone>134222225555</phone>
		<email>lisi@qq.com</email>
		<qq>432222222</qq>
	</contact>
</contactList>

给出案例和解释:

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.Text;
import org.dom4j.io.SAXReader;
import org.junit.Test;
/**
 * 练习-完整读取xml文档内容
 * @author APPle
 *
 */
public class Demo3 {

	@Test
	public void test() throws Exception{
		//读取xml文档
		SAXReader reader = new SAXReader();
		Document doc = 
				reader.read(new File("./src/contact.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();
		//System.out.println(content);
		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()+">");
		
		
		
		
	}
}


posted on 2016-05-26 22:16  王小航  阅读(397)  评论(0编辑  收藏  举报

导航