zoukankan      html  css  js  c++  java
  • 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()+">");
    		
    		
    		
    		
    	}
    }
    


  • 相关阅读:
    bootstrap modal 垂直居中对齐
    BootStrap同时显示多个Modal解决方案
    Echarts使用及动态加载图表数据 折线图X轴数据动态加载
    jQuery操纵DOM元素属性 attr()和removeAtrr()方法使用详解
    jQuery修改class属性和CSS样式
    JS中的substring和substr函数的区别
    select into from和insert into select from两种表复制语句区别
    SQL查询遍历数据方法一 [ 临时表 + While循环]
    JSSDK实现微信自定义分享---java 后端获取签名信息
    Spring 自带的定时任务Scheduled
  • 原文地址:https://www.cnblogs.com/wanghang/p/6299750.html
Copyright © 2011-2022 走看看