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();
}
}
xml文件处理的好工具--读取数据篇--cnjsp.org
最新推荐文章于 2022-10-22 17:49:27 发布