您的位置:首页 > 其它

SAX解析XML的例子.

2006-07-12 23:39 429 查看
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import java.util.*;
import java.io.File;

public class TestSax
{
 public static void main(String dd[]){
  try{
  SAXBuilder sh = new SAXBuilder();
  Document dc = sh.build(new File("fibo.xml"));
  Element el = dc.getRootElement();
  String name = el.getName();
  System.out.println(name);
  List elch = el.getChildren();
  System.out.println(elch.toString());
  Iterator it = elch.iterator();
  while(it.hasNext()){
  Element e = (Element)it.next();
  String b = e.getAttributeValue("ProdTypeId");
  System.out.println(b);
   List temp = e.getChildren("ab");
          Element te = (Element) temp.get(0);
         String  result = te.getTextNormalize();
   System.out.println("-----"+result);
  }
  }catch(Exception e){
   e.printStackTrace();
  }
 }
}
 

 
先招呼段程序.別看這段沒什么,不過是SAX解析XML的一個小程序..因為要讀取xml.所以就從這個地方入手.網上擻索暸些資料.把xml的文件也放上來..呵呵
 
<?xml version="1.0" encoding="UTF-8"?>
<BusiConfig>
 <item ProdTypeId="00002" ConnName="1" >
  <ab>aaa</ab>
 </item>  
</BusiConfig>

 
哈哈..順便把註釋我給加上..
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import java.util.*;
import java.io.File;

public class TestSax
{
 public static void main(String dd[]){
  try{
  SAXBuilder sh = new SAXBuilder();                                 //construct Builder
  Document dc = sh.build(new File("fibo.xml"));               //load
  Element el = dc.getRootElement();                                //root
  String name = el.getName();                                          //root's name
  System.out.println(name);                                             //print name
  List elch = el.getChildren();                                            //get sub node
  System.out.println(elch.toString());                               //print
  Iterator it = elch.iterator();                                            //iterator
  while(it.hasNext()){                                                        //if it have next is true continute
  Element e = (Element)it.next();                                      //load object
  String b = e.getAttributeValue("ProdTypeId");              //get attribute
  System.out.println(b);                                                    //print b
   List temp = e.getChildren("ab");                                    //get subnode
          Element te = (Element) temp.get(0);                      //load first object
         String  result = te.getTextNormalize();                    //read message
   System.out.println("-----"+result);                                 //print
  }
  }catch(Exception e){
   e.printStackTrace();
  }
 }
}
 
最后的運行結果是:
---------- java ----------
BusiConfig
[[Element: <item/>]]
00002
-----aaa
输出完成 (耗时 0 秒) - 正常终止
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息