xml文件处理的好工具--读取数据篇--cnjsp.org

http://www.cnjbb.org/thread.jsp?boardid=46&threadid=43597&pageno=1&perpage=10&mode=block
在这里会让你们更快的学习java!不但定期给出好的教程,而且有java牛人给你制定计划和回答问题!cnjsp.org很好!

本文介绍一个xml处理的好工具,让大家先睹为快-----jdom.
下面简单地介绍他的应用.
(1)大家知道处理xml文件的两种基本方法:DOM;SAX.
(2)jdom不需要开发人员懂得如何建立这两种解析器;因为jdom已经为你设置好了.
(3)简单的使用方法如下:
<?xml version="1.0" encoding="UTF-8"?>
<car vin="123">
    <make>Toyota</make>
  <model>Celica</model>
  <year>1997</year>
  <color>green</color>
  <license state="CA">1ABC234</license>
</car>
将这个文件保存在c:/car.xml
现在我们要读取其中的数据:
(1)产生解析器,并创建Document文档对象
           SAXBuilder builder = new SAXBuilder();
           Document doc = builder.build(new File(“c:/car.xml“));
(2)jdom把以<>开始和以</>结束的叫做Element;把<car vin="123">中的vin称为Attribute;
    把<make>Toyota</make>中的Toyota称为Text(Content).
           Element root=doc.getRootElement();
           String vin=root.getAttributeValue(“vin“);//输出: 123
           Element make=root.getChild(“make“);//如果有相同的标签,List list=root.getChildren(“标签名“);
           String make_text=make.getText();//输出: Toyota
(3)要得到其他的标签数据,如上面.
(4)测试代码:
import org.jdom.*;
public  class Test{
   public static void main(String arg[]){
          try {
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(new File(“c:/car.xml“));

            Element root=doc.getRootElement();
           String vin=root.getAttributeValue(“vin“);//输出: 123
            System.out.println(vin);

           Element make=root.getChild(“make“);//如果有相同的标签,List list=root.getChildren(“标签名“);
           String make_text=make.getText();//输出: Toyota
           System.out.println(make_text);

           Element model=root.getChild(“model“);
           String model_text=make.getText();
            System.out.println(model_text);

          Element year=root.getChild(“year“);
           String year_text=make.getText();
          System.out.println(model_text);

          Element color=root.getChild(“color“);
           String color_text=make.getText();
          System.out.println(color_text);

          Element license=root.getChild(“license “);
          String  state=license.getAttributeValue(“state“);
           String license _text=make.getText();
           System.out.println(state);
           System.out.println(licence_text);
         
        } catch(Exception e) {
            e.printStackTrace(); 
       }
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值