六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 44|回复: 0

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

[复制链接]

升级  36.67%

29

主题

29

主题

29

主题

秀才

Rank: 2

积分
105
 楼主| 发表于 2013-2-3 14:38:10 | 显示全部楼层 |阅读模式
<?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>
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表