使用 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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值