Eclipse下jdom配置及用之生成、解析xml文档

来源:互联网 发布:怎么看淘宝客开没开通 编辑:程序博客网 时间:2024/06/08 02:56

1、jdom配置:

      由官方网站下载jdom最新版本,将之加入E:\Eclipse\jre\lib\ext.  在eclipse下import org.jdom2.*; ,即可成功。不过在引入类时,最好使用单类型引入。

2、eclipse 设置

       在用语句:Document doc=new Document(); 创建文档时,发现Document类不可访问,因为有些库的访问被限制,不知为何。

       设置方法如下:Eclipse 菜单Windows---->Preferences---->Java----->Compiler------>Error/Warnings----->Deprecated and Restrict ed API------>Forbidden references----->Warnings.

3. 生成XML文件源代码

   

import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.output.Format;import org.jdom2.output.XMLOutputter;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;public class Node{public static void main(String[] args){Document doc=new Document();Element book=new Element("book");book.setAttribute("title", "A");Element chpt1=new Element("chpt1");chpt1.setAttribute("name","chapter 1");Element chpt2=new Element("chpt2");chpt2.setAttribute("name", "chapter 2");book.addContent(chpt1);book.addContent(chpt2);doc.addContent(book);Format format=Format.getPrettyFormat();format.setEncoding("GBK");XMLOutputter xmlfile=new XMLOutputter(format);try{xmlfile.output(doc, new FileOutputStream(new File("d:/exa.xml")));xmlfile.output(doc,System.out);}catch(IOException e){System.out.println("Output file error!");}}} 


4. 运行结果:

<?xml version="1.0" encoding="GBK"?>
<book title="A">
  <chpt1 name="chapter 1" />
  <chpt2 name="chapter 2" />
</book>

 

5、解析XML文件源代码(以刚生成的文件为输入)

import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.input.SAXBuilder;import java.util.List;import java.util.ArrayList;import java.io.File;public class Node{public static void main(String[] args)throws Exception{    SAXBuilder builder=new SAXBuilder();    Document doc=builder.build(new File("d:/a.xml"));        Element book=doc.getRootElement();    List<Element> list=new ArrayList<Element>();    list=book.getChildren("chpt1");        for(int i=0;i<list.size();i++)    {    Element e=list.get(i);    String name=e.getAttributeValue("name");    System.out.println(name);    }    }} 

6、运行结果:

chapter 1

 

总结:STL使用不熟。

原创粉丝点击