jdom入门

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();
}
 

你可能感兴趣的:(xml)