学习JDOM(2)

本文详细介绍JDOM库的基本使用方法,包括Document和Element类的操作、属性管理及命名空间处理等。适用于希望快速上手JDOM进行XML文件处理的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

四、JDOM的使用方法
1、Document类
(1)Document的操作方法:

Element root = new Element("tree");
Document doc = new Document(root);
root.setText("Department");

(2)从文件、流、系统ID、URL得到Document对象

SAXBuilder builder = new SAXBuilder();
Document doc = bulider.build(url);
Element element = doc.getRootElement();

(3)DOM的document和JDOM的Document之间的相互转换方法

DOMBuilder builder = new DOMBuilder();
org.jdom.Document jdomDocument = builder.build(docDocument);
DomOutputter converter = new DomOutputter();
org.w3c.dom.Document domDocument = comverter.output(jdomDocument);

2、XML文档输出
略。
3、Element类

Element root = doc.getRootElement(); //获得根元素
List allChildren = root.getChildren(); //获得所有子元素的list
List namedChildren = root.getChildren("name"); //获得指定名称子元素的list
Element child = root.getChild("name"); //获得指定名称的第一个元素

allChildren.remove(3); //删除第4个元素,基数从0开始
allChildren.removeAll(root.getChildren("cs")); //删除叫cs的子元素
root.removeChildren("cs"); //删除叫cs的子元素

allChildren.add(new Element("cs")); //增加叫cs的子元素
root.addContent(new Element("cs")); //增加叫cs的子元素

allChildren.add(0, new Element("first")); //增加第一个节点,叫“first”

(2)移动Elements:

Element movable = new Element("movable");
parent1.addContent(movable);
parent1.removeContent(movable);
parent2.addContent(movable);

(3)Element的text内容读取

<description>
A cool Demo
</description>

String desc = element.getText();

或者
String desc = element.getTextTrim();

(4)Element内容修改
element.setText(""); //注意回车键也被解析成为Text类
4、Attribute类

<table width="100%" border="0"> </table>

String width = table.getAttributeValue("width"); //获得attrubute
int border = table.getAttribute("border").getIntValue();
table.setAttribute("vspace", "0"); //设置attribute
table.removeAttribute("vapace"); //删除一个attribute
table.getAttributes().clear(); //删除全部attribute

5、处理指令的操作
此处没有看懂,暂且略
6、命名空间操作

<xhtml:html xmlns:xhtml="http://www.w3.org/1999/xhtml">
<xhtml:title>Home Page</xhtml:title>
</xhtml:html>

Namespace xhtml = Namespace.getNamespace("xhtml", "http://www.w3.org/1999/xhtml");

List kids = html.getChildren("title", xhtml);
Element kid = html.getChild("title", xhtml);
kid.addContent(new Element("table", xhtml));

7、XSLT格式转换

public static Document transform(String stylesheet,Document in)
throws JDOMException
{

try
{

Transformer transformer = TransformerFactory.newInstance()
.newTransformer(new StreamSource(stylesheet));

JDOMResult out = new JDOMResult();

transformer.transform(new JDOMSource(in), out);

return out.getDeocument();

}
catch (TransformerException e)
{
throw new JDOMException("XSLT Trandformation failed", e);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值