六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 105|回复: 0

学习JDOM(2)

[复制链接]

升级  66.67%

42

主题

42

主题

42

主题

秀才

Rank: 2

积分
150
 楼主| 发表于 2013-2-7 19:08:51 | 显示全部楼层 |阅读模式
四、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();  //获得所有子元素的listList namedChildren = root.getChildren("name");  //获得指定名称子元素的listElement 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"); //获得attrubuteint border = table.getAttribute("border").getIntValue();table.setAttribute("vspace", "0"); //设置attributetable.removeAttribute("vapace"); //删除一个attributetable.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);     }}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

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