XML 文件以下:
<?xml version='1.0' encoding='utf-8'?>
<links>
<link>
<text>JSP Insider</text>
<url>http://www.jspinsider.com</url>
<date>
<day>2</day>
<month>1</month>
<year>2001</year>
</date>
</link>
<link>
<text>ASP Insider</text>
<url>http://www.Aspinsider.com</url>
<date>
<day>2</day>
<month>1</month>
<year>2001</year>
</date>
</link>
</links>
與XML對應的JAVA對象:
package tiany.lijun.readxml;
public class obj
{
String text=null;
String url=null;
Datee d=null;
public obj()
{
d=new Datee();
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public Datee getD()
{
return d;
}
public void setD(Datee d)
{
this.d = d;
}
public class Datee //內置對象 對應日期
{
String day=null;
String month=null;
String year=null;
public String getDay()
{
return day;
}
public void setDay(String day)
{
this.day = day;
}
public String getMonth()
{
return month;
}
public void setMonth(String month)
{
this.month = month;
}
public String getYear()
{
return year;
}
public void setYear(String year)
{
this.year = year;
}
}
}
讀取XML的主文件:
package tiany.lijun.readxml;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class readxml extends DefaultHandler
{
public obj vo;
private String str;
private HashSet set;
public void endDocument() throws SAXException
{
}
public void startDocument() throws SAXException
{
set = new HashSet();
}
public void startElement(String p0, String p1, String p2, Attributes p3) throws SAXException
{
if (p2.equals("link"))
{
vo = new obj();
}
}
public void endElement(String p0, String p1, String p2) throws SAXException
{
if (p2.equals("text"))
{
vo.setText(str);
}
else if (p2.equals("url"))
{
vo.setUrl(str);
}
else if (p2.equals("link"))
{
set.add(vo);
vo = null;
}
else if (p2.equals("links"))
{
display();
}
else if (p2.equals("day"))
{
vo.getD().setDay(str);
}
else if (p2.equals("month"))
{
vo.getD().setMonth(str);
}
else if (p2.equals("year"))
{
vo.getD().setYear(str);
}
}
public void characters(char[] p0, int p1, int p2) throws SAXException
{
str = new String(p0, p1, p2);
}
public void display()
{
Iterator it = set.iterator();
while (it.hasNext())
{
obj v = (obj) it.next();
System.out.println(v.getText());
System.out.println(v.getUrl());
System.out.println(v.getD().getDay());
System.out.println(v.getD().getMonth());
System.out.println(v.getD().getYear());
System.out.println("-------------------------------");
}
}
static public void main(String[] args)
{
String filename = null;
boolean validation = false;
filename = "tomcat-usersw.xml";
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = null;
try
{
saxParser = spf.newSAXParser();
}
catch (Exception ex)
{
System.err.println(ex);
System.exit(1);
}
try
{
saxParser.parse(new File(filename), new readxml());
}
catch (SAXException se)
{
System.err.println(se.getMessage());
System.exit(1);
}
catch (IOException ioe)
{
System.err.println(ioe);
System.exit(1);
}
}
}
回覆中爲SAX解析XML方式
JDOM解析XML文件
二、jdom
package org.lyj.xml;
import org.jdom.output.Format;
import org.jdom.Document;
import java.io.IOException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.jdom.JDOMException;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class JdomWriter {
public JdomWriter() {
}
public void write(){
try {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build("aa.xml");
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("utf-8"));
outputter.output(doc, new java.io.FileOutputStream("bb.xml"));
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
JdomWriter jd = new JdomWriter();
jd.write();
}
}
Java解析XML文件2007-08-17 11:17package com.yc.ycportal.ge.util; import java.io.FileInputStream; import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.util.ResourceBundle; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * @author * 本類的做用是對properties和xml文件的解析,重點在於包括xml文件的兩種解析方式 * 如今有三種用於Java的流行xml解析技術,文檔對象模型(Document Object Model,DOM),基於W3C的 * 成熟標準,二、用於XML的簡單API(Simple API for XML),第一個被普遍採用的用Java編寫的XML API * 是一個事實上的標準,3、用於XML的數據流API(Straming API for XML,StAX),JSR-173中採用 * 的一個新解析模型 */ public class ParseFile { public static ParseFile getInterface(){ return new ParseFile(); } /**解析Properties文件獲取數據信息*/ /** *properties的文件格式爲 *username=sa *userpass=123以第一等號爲標準,後面爲它的值 */ public List getPropertes(String fileName){ List list = null; ResourceBundle rb = ResourceBundle.getBundle(fileName); list.add(rb.getString("username")); list.add(rb.getString("userpass")); return list; } /**用SAX方式解析XML文件獲取數據信息,建立一個解析XML文件的內部類解析器*/ class ParseXML extends DefaultHandler{ //全部的方法是子類重寫父類的方法 String currentName = null; StringBuffer currentValue = new StringBuffer(); Properties properties = null; //接收元素開始的通知。 //默認狀況下,不執行任何操做。應用程序編寫者能夠在子類中重寫此方法,以便在每一個元素的開始處採起特定的操做 public void startElement(String uri,String localName,String qName,Attributes attributes)throws SAXException{ this.currentValue.delete(0, this.currentValue.length()); this.currentName = qName; } //接收元素中字符數據的通知 //默認狀況下,不執行任何操做。應用程序編寫者能夠重寫此方法,以便對每塊字符數據採起特定的措施 //如將該數據添加到節點或緩衝區,或者將該數據打印到文件。 public void characters(char[] ch,int start,int length)throws SAXException{ this.currentValue.append(ch,start,length); } //接收元素結束的通知 //默認狀況下,不執行任何操做。應用程序編寫者能夠在子類中重寫此方法,以便在每一個元素的結束處採起特定的操做 //如,結束樹節點或將輸出寫入文件。 public void endElement(String uri,String localName,String qName)throws SAXException{ this.properties.put(qName.toLowerCase(), this.currentValue.toString().trim()); } //返回存儲XML信息數據的properties public Properties getProperties(){ return this.properties; } } public List getSAXXml(String fileName)throws Exception{ List list = null; ParseXML parsexml = new ParseXML(); Properties properties = null; SAXParserFactory factory = SAXParserFactory.newInstance(); //若是由此代碼生成的解析器將提供對 XML 名稱空間的支持,則爲 true;不然爲 false。 factory.setNamespaceAware(false); //指定由此代碼生成的解析器將驗證被解析的文檔。默認狀況下,其值設置爲 false factory.setValidating(false); SAXParser parser = factory.newSAXParser(); //使用指定的DefaultHandler將指定文件的內容解析爲 XML。 parser.parse(fileName, parsexml); properties = parsexml.getProperties(); Enumeration em = properties.keys(); while(em.hasMoreElements()){ list.add(properties.get(em.nextElement().toString())); } return list; } /**用Dom方式解析XML文件獲取數據信息,比較容易理解和掌握的一種方式very good*/ public List getDOMXml(String fileName)throws Exception{ List list = null; SAXBuilder builder = new SAXBuilder(); Document document = builder.build(new FileInputStream(fileName)); //document.getRootElement()獲取根節點返回一個Element List listchild = document.getRootElement().getChildren("table"); for(int i=0;i<listchild.size();i++){ Element e = (Element)listchild.get(i); String tableName = e.getChild("tablename").getText(); List nextchild = e.getChild("fields").getChildren("field"); list.add(tableName); for(int j=0;j<nextchild.size();j++){ Element child = (Element)nextchild.get(j); list.add(child.getAttributeValue("name")); } } //返回的List的結構是以表名爲0個索引位置後面依次爲表的字段名稱,附帶XML文件描述 return list; } } <?xml version="1.0" encoding="gb2312" ?> <tables> <table> <tablename>dic_rate_zhwd</tablename> <fields> <field name="organ_id" type="string"/> <field name="business_id" type="string"/> <field name="business_name" type="string"/> <field name="rate" type="double"/> </fields> </table> </tables>