清水幽香 发表于 2013-2-3 14:38:10

使用 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")) ;}}

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

roothello            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>
页: [1]
查看完整版本: 使用 JDOM 解析一个 XML 文档(二)