应用 JDOM 解析一个 XML 文档(二)

使用 JDOM 解析一个 XML 文档(二)
<?xml version="1.0" encoding="GBK"?>
<root>
    <!--This is my comments-->
    <hello google="www.google.com">
        <world test="hehe">
            <aaa a="b" x="y" gg="mm">text content</aaa>
        </world>
    </hello>
</root>




package com.syh.xml.jdom;

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

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * 读取(解析)一个 XML 文档 ---> 将文档加载到内存中
 * @author Administrator
 *
 */

public class JDomTest2 {

	public static void main(String[] args) throws Exception {
		
		//构造出 JDOM 的解析器
		SAXBuilder builder = new SAXBuilder() ;
		
		// 将文档加载到内存当中 ,并拿到了这个 XML 文档的根节点
		Document doc = builder.build(new File("jdom.xml")) ;
		
		//获得 XML 文档的根元素
		Element rootEle = doc.getRootElement() ;
		System.out.println(rootEle.getName());
		
		//获得指定的元素
		Element hello = rootEle.getChild("hello") ;
		System.out.println(hello.getName());
		System.out.println(hello.getText());
		
		//获得元素的属性
		List<Attribute> list = hello.getAttributes() ;
		
		for(Iterator<Attribute> iter = list.iterator() ; iter.hasNext() ; ) {
			Attribute attr = iter.next() ;
			
			String attrName = attr.getName() ;
			String attrValue = attr.getValue() ;
			
			System.out.println(attrName + " = " + attrValue);
		}
		
		//删除元素
		hello.removeChild("world") ;
		
		
		
		
		
		
		XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setIndent("    ")) ;
		
		out.output(doc, new FileOutputStream("jdom2.xml")) ;
		
	}
	
}



下面是在控制台上输出的结果:

root
hello

        
    
google = www.google.com



下面是在解析后再次产生一个 XML 文档的结果:
<!-- jdom2.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <!--This is my comments-->
    <hello google="www.google.com" />
</root>