jdom入门

本文介绍使用Java的JDOM库来创建、读取、更新和保存XML文档的方法。包括如何构建XML文档、添加属性与元素、注释的使用、子元素的操作、文档输出及XML解析等关键步骤。

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

1. 建立 XML 文档样本
<?xml version="1.0" encoding="UTF-8"?>
<car vin="123fhg5869705iop90">
  <!--Description of a car-->
  <make>Toyota</make>
  <model>Celica</model>
  <year>1997</year>
  <color>green</color>
  <license state="CA">1ABC234</license>
</car>
2. 创建一个 Document
//得到一个唯一的根元素
Element carElement = new Element("car");
//Document 将 Element 放在它的构造器中
Document myDocument = new Document(carElement);
3. 添加一个 Attribute
carElement.addAttribute(new Attribute("vin", "123fhg5869705iop90"));
4. 元素和子元素
Element make = new Element("make");
make.addContent("Toyota");
carElement.addContent(make);
 5. 用简洁形式添加元素
carElement.addContent(new Element("make").addContent("Toyota"));
7. 添加一条注释
carElement.addContent(new Comment("Description of a car"));
8. 访问子元素
Element yearElement = carElement.getChild("year");
9. 除去子元素
boolean removed = carElement.removeChild("year");
 
10. 将 JDOM 转化为 XML 文本
try {
    XMLOutputter outputter = new XMLOutputter("  ", true);
    outputter.output(myDocument, System.out);
} catch (java.io.IOException e) {
    e.printStackTrace();
}
11. 使用 FileWriter 输出 XML
FileWriter writer = new FileWriter("/some/directory/myFile.xml");
outputter.output(myDocument, writer);
writer.close();
12. 使用 SAXBuilder 对 XML 文件进行语法分析
try {
  SAXBuilder builder = new SAXBuilder();
  Document anotherDocument =
    builder.build(new File("/some/directory/sample.xml"));
} catch(JDOMException e) {
  e.printStackTrace();
} catch(NullPointerException e) {
  e.printStackTrace();
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值