JDOM 详解

本文介绍了如何使用JDOM库创建、修改和输出XML文档。通过实例展示了如何创建XML元素、设置属性、添加内容,并使用不同格式输出XML文件。同时,也演示了从XML文件读取数据的方法。

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


方法链的编程风格(method chain style)
Element e = new Element ("test");
e.setAttribute("aa","bb");
e.setAttribute("cc","a");
e.setAttribute("aa","bb").setAttribute("cc","a");

对于JDOM的Format类的getRawFormat方法,通常用于XML数据网络传送,因为这

种格式会去掉所有不必要的空白,因此能减少网络传送的数据量。
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom.*;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class JdomTest1
{
public static void main(String[] args) throws FileNotFoundException,

IOException
{
    Document document = new Document();
    Element root = new Element("root");
    document.addContent(root);
    Comment comment= new Comment("This is a comment");
    root.addContent(comment);
    Element e = new Element("hello");
    e.setAttribute("sohu","www.suhu.com");
    root.addContent(e);
    Element e2 = new Element("world");
    Attribute attr = new Attribute("test","hehhe");
    e2.setAttribute(attr);
    e.addContent(e2);
    e2.addContent(new Element("aaa").setAttribute

("a","b").setAttribute("x","y").setAttribute("gg","hh").setText("text

content"));
    Format format = Format.getPrettyFormat();
    format.setIndent("    ");
    format.setEncoding("UTF-8");
    XMLOutputter out = new XMLOutputter(format);
    out.output(document,new FileOutputStream("jdom.xml"));
    
    
}
}


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;


public class JdomTest2
{
public static void main(String[] args) throws IOException,

IOException, JDOMException
{
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(new File("jdom.xml"));
    Element element = doc.getRootElement();
    System.out.println(element.getName());
    
    Element hello=element.getChild("hello");
    System.out.println(hello.getText());
    List list=hello.getAttributes();
    for(int i=0;i<list.size();i++)
    {
        Attribute attr = (Attribute)list.get(i);
        
        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"));
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值