使用JDOM和DOM4j解析XML

   一、JDOM简介:
     1是一个开源的项目,基于树形结构,利用纯java的技术对XMl文档实现解析,生成,序列化以及多种操作。

2.JDOM直接为Java编程服务,利用更为强有力的Java语言的诸多特性(方法重载,集合等概念),把SAX和DOM的功能有效的结合起来。

 3.JDOM是用Java语言读,写,操作XML的新API,函数,在直接,简单和高效的前提下,这些API函数被最大限度的优化。

这里有有关JDOM的详细介绍:http://baike.so.com/doc/1003561.html

 

JDOM由以下几个包构成:

  Org.jdom包含了所有的XML文档要素的Java类

  Org.jdom.adapters包含了与dom适配的Java类

  Org.jdom.filter包含了XML文档的过滤器的类

  Org.jdom.input包含了读取XML文档的类

  Org.jdom.output包含了写入XML文档的类

  Org.jdom.transform包含了将jdomxml文档接口转换为其他文档接口。

  Org.jdom.xpath包含了对XML文档XPath操作的类。

 

解析XML的开源框架:JDOM,DOM4j.

 

1.对于JDOM的format类的getRawFormat方法,通常用于XML数据的网络传输,因为这种格式会去掉所有不必要的空白,因此能够减少网络传输的数据量。

2.保存到硬盘上,建议使用getPrettyFormat()方法,

 

二、JDOM使用实例:

public class MyTestJdom {
    public static void main(String[] args) {
    	//MyTestJdom.addChildElement(new String []{"college","grade","classes","students"},"studentTest.xml",null);
    
    }
    
    /**
     * 使用JDOM生成简单的XML文档
     */
    public static void createDocument(){
    	
    	//注意标签或者属性不能以数字开头,否则生成报错
    	//创建根节点
        Element  root = new Element("schools");
    	root.setAttribute(new Attribute("name", "**大学")).setAttribute(new Attribute("addr", "吉林省长春市"));
    	Document document = new Document(root);  //将根节点放入Document对象中
    
    	//创建学院
    	Element college = new Element("college");
    	college.setAttribute("name","计算机科学技术").setAttribute("counselor","张三");
    	
    	//创建年级
    	Element grade = new Element("grade");
    	grade.setAttribute("name","12");
    	
    	//创建班级
    	Element classes = new Element("classes");
    	classes.setAttribute("className","4班").setAttribute("monitor","王五");
    	
    	
    	//分步添加
    	Element student = new Element("students");
    	student.setAttribute("xuehao","3242345");
    	Element name = new Element("name");
    	name.setText("李四");
    	Element sex = new Element("sex");
    	sex.setText("男");
    	Element age = new Element("age");
    	age.setText("23");
    	//添加student里的元素
    	student.addContent(name);
    	student.addContent(sex);
    	student.addContent(age);
    	
    	//使用方法链,一次性添加
    	Element  student1 = new Element("students");
    	student1.setAttribute("xuehao","3242356").
    	       addContent(new Element("name").setText("小芳")).
    	       addContent(new Element("sex").setText("女")).
    	       addContent(new Element("age").setText("21"));
    	//使用方法链,一次性添加
    	Element  student2 = new Element("students");
    	student2.setAttribute("xuehao","3242312").
    	       addContent(new Element("name").setText("小郑")).
    	       addContent(new Element("sex").setText("女")).
    	       addContent(new Element("age").setText("22"));
    	//添加classes里的元素
    	classes.addContent(student);
    	classes.addContent(student1);
    	classes.addContent(student2);
    	//添加年级里的元素
    	grade.addContent(classes);
    	college.addContent(grade);
    	root.addContent(college);
        
    	//创建xml文档
    	createXML( document,"studentTest.xml",null);

    }
    
    /**
     * 创建xml文档,当文档更改时,使用该文档进行重新创建
     * @param document
     * @param fileName
     * @param filePath
     */
    public static void createXML(Document document,String fileName,String filePath){
    	//设置xml文档格式
    	Format format = Format.getPrettyFormat();
    	format.setIndent(" ");
    	XMLOutputter  output = new XMLOutputter(format);
    	try {
		  output.output(document, new FileOutputStream(fileName));
    	  System.out.println("---------------------创建完毕--------------");
    	} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    /**
     * 读取xml
     * @param fileName
     * @param filePath
     * @return Document对象
     */
    public static Document getDocument(String fileName,String filePath){
    	  SAXBuilder  builder = new SAXBuilder();
    	  Document document = null;
			try {
			 document = builder.build(new File(fileName));
			} catch (JDOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return document;
    }
    
    
    /**
     * 使用JDOM解析XML文档
     */
    public static void getXml(){
    	 	Document  document = getDocument("studentTest.xml",null);  //在当前项目目录下,文件路劲为null
			Element  root = document.getRootElement();  //获取根元素schools
			System.out.println("rootName = "+root.getName()+" : "+root.getAttributeValue("name")+"\n");
    	  
			Element  college = root.getChild("college");  //得到colleg元素
			System.out.println(college.getName()+": "+college.getAttributeValue("name")+"\n");
    	  
			Element grade = college.getChild("grade") ;
			System.out.println("子元素个数:"+grade.getContentSize()+"\n");
			
			Element classes = grade.getChild("classes");  
			System.out.println("班级"+classes.getAttributeValue("className")+" :班长 "+classes.getAttributeValue("monitor")+"\n");
    	  
			List  eleList = classes.getChildren(); //获取classes下的学生元素
			for (Object object : eleList) {
				Element student = (Element)object;
				System.out.println("学号: "+student.getAttributeValue("xuehao")+" 姓名: "+student.getChildText("name")+" 性别: "+student.getChildText("sex")+" 年龄: "+student.getChildText("age"));
			}
			System.out.println("--------------------分析完毕------------------");
    }
    
    /**
     * 为DOM树下的第elemArray的elemArray[n-2]添加子元素
     * @param parentElement
     */
    public static  void addChildElement(String elemArray[],String fileName,String filePath){
    	Document document = getDocument(fileName,null);
    	
    	//先获取根元素节点
    	Element root = document.getRootElement();
    	System.out.println("rootName "+root.getName());
    	Element element = null;
    	for(int i =0;i< elemArray.length;i++){
    		element = root.getChild(elemArray[i]);
    		root = element;
    	}
    	
    
    	element = new Element(root.getName());
    	element.setAttribute("xuehao","3242311").
	       addContent(new Element("name").setText("小肥")).
	       addContent(new Element("sex").setText("男")).
	       addContent(new Element("age").setText("22"));
    	root.getParentElement().addContent(element);

    	System.out.println("子元素个数: "+root.getContentSize());
    	createXML( document, fileName,null); //重新创建
    }
}

Xml 创建代码

<?xml version="1.0" encoding="UTF-8"?>
<schools name="**大学" addr="吉林省长春市">
 <college name="计算机科学技术" counselor="张三">
  <grade name="12">
   <classes className="4班" monitor="王五">
    <students xuehao="3242345">
     <name>李四</name>
     <sex>男</sex>
     <age>23</age>
    </students>
    <students xuehao="3242356">
     <name>小芳</name>
     <sex>女</sex>
     <age>21</age>
    </students>
    <students xuehao="3242312">
     <name>小郑</name>
     <sex>女</sex>
     <age>22</age>
    </students>
    <students xuehao="3242311">
     <name>小肥</name>
     <sex>男</sex>
     <age>22</age>
    </students>
   </classes>
  </grade>
 </college>
</schools>

DOM4j使用实例:
public class MyTestDom4j {
    public static void main(String[] args) {
    	Document doc = MyTestDom4j.createDocument();
    	MyTestDom4j.outputByUTF(doc, "bookx.xml", null);
    	doc = getDoc("bookx.xml",null);
    	
    	MyTestDom4j.getinfo(doc);
    }
    
    /**
     * 创建Document对象
     * @return
     */
    public static Document createDocument(){
    	Element  root = DocumentHelper.createElement("books");
		Document  document = DocumentHelper.createDocument(root);  //设置根节点
		Element book = root.addElement("book");
		book.addAttribute("type", "英语").addAttribute("author", "李阳");
		Element publishTime = book.addElement("publishTime");
		publishTime.setText("2013-09-08");  //设置文本内容
		Element publish = book.addElement("publisher");
		publish.setText("延边出版社");
		Element bookName = book.addElement("name");
	    bookName.setText("简单英语词典");
	    return document;
    }

    /**
     * 将创建的xml文档输出到控制台
     * @param document
     */
    public static void outputToConsole(Document document){
    	XMLWriter writer = new XMLWriter();
		try {
			writer.write(document);  //输出到控制台
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    /**
     * 写到硬盘中
     * @param document
     */
    public static void outputByUTF(Document document,String fileName,String filePath){
        OutputFormat  format = new OutputFormat("  ",true);
		//写到硬盘,使用文件字节输出流-----使用UTF-8编码
		try {
			XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(fileName),format);
			xmlWriter.write(document);
			xmlWriter.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    /**
     * 
     * @param document
     * @param fileName
     * @param filePath
     */
    public static void  outputByGBK(Document document,String fileName,String filePath){
    	OutputFormat  format1 = new OutputFormat("  ",true);
		format1.setEncoding("GBK");  //注意设置编码格式,否则中文出现乱码
		//使用字符流---使用的是DBK对中文编码
		try {
			XMLWriter xmlWriter2 = new XMLWriter(new FileWriter(fileName),format1);
			xmlWriter2.write(document);
			xmlWriter2.flush();  //刷新缓存
			xmlWriter2.close(); //记住,要刷新缓存或者关闭xml输出流,否则文件为空
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
   
    /**
     *解析返回Document对象
     * @param fileName
     * @param filePath
     * @return
     */
    public static Document getDoc(String fileName,String filePath){
    	//第一种解析方式,第二种DOmReader(JAXP方式转换而来)
    	SAXReader saxReader = new SAXReader();
    	Document doc = null;
		try {
			 doc = saxReader.read(new File(fileName));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return doc;
    }
    
    /**
     * 使用Java自带的方式解析
     * @param fileName
     * @param filePath
     * @return
     */
    public static Document getDoc1(String fileName,String filePath){
    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		org.w3c.dom.Document document = null;
		try {
			DocumentBuilder  db = dbf.newDocumentBuilder();
			document = db.parse(new File("student2.xml"));
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		DOMReader domReader = new DOMReader();
		//将JAXP的Document转换成Dom4j的Document
		Document doc2= domReader.read(document);
		return doc2;
    }

    
    //解析xml
    public static void getinfo(Document doc){
    	Element  root = doc.getRootElement();
    	List eleList = root.elements();
    	for (Object object : eleList) {
    		Element ele = (Element)object;
    		System.out.println(ele.getName());
		}
    }
}




Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐