Xml解析
Xml文件:
1.声明:<?xml version=”1.0” standalone=”yes/no” encoding=”UTF-8/GB2312” ?>
2.是否有DTD(文档类型定义)<!DOCTYPE typeofdoc SYSTEM/PUBLIC “dtdname.dtd”>
3.所有标识必须有相应的结束标志,空标识也必须关闭如:<br/>,严格区分大小写
4.<![CDATA[这样可以输出一些特殊符号如<]]>//DTD字符或文本:<!ELEMENT user(#PCDATA)>
5.Namespaces(xml文件定位DTD文件):<document xmlns:xl=”URL”><xl:table>wood</table>
6.entity实体:<!DOCTYPE filename[<!ENTITY name “content”>]> 调用;&name
7.DTD文件:<!ELEMENT datasource(driver,url,user,password)>//a:一次;a?:<=1;a+:>=1;a*:
8.实例;<database-conf>
<datasource>
<driver>com.mysql.jdbc.Driver</driver>
<url>jdbc:mysql://localhost:3306/test </url>
<user>root</user>
<password></password>
</datasource>
</database-conf>
9.读树元素:用StringBuffer读入元素,最后存在Hashtable的Properties里面,并作为返回类型
import java.util.Properties;import org.xml.sax.Attributes;
import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;
public class XMLConfigParser extends DefaultHandler{//可重载startElement等方法
//DefaultHandler继承了所有ContentHandler,Error,DTDHandler,EntityResolver接口
private Properties props;//继承了Hashtable,表示一个持久属性集合
private StringBuffer currentValue=new StringBuffer();//类似字符串缓冲区,不能修改
public XMLConfigParser(){ this.props=new Properties(); }
public Properties getProps(){ return this.props; }
public void startElement(String uri,String localName,String qName,
Attributes attributes)throws SAXException{//Attributes是xml属性列表接口
currentValue.delete(0,currentValue.length()); }
public void characters(char[] ch,int start,int length)throws SAXException{
currentValue.append(ch,start,length); }
public void endElement(String uri,String localName,String qName)throws SAXException{
props.put(qName.toLowerCase(), currentValue.toString().trim());}}//小写
10.调用SAX解析: import java.net.URL;import java.util.Properties;
import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;
public class DatabaseConfigParser {private Properties props;
public Properties getProps(){ return this.props;}
public void parse(String filename)throws Exception{
XMLConfigParser handler=new XMLConfigParser();
SAXParserFactory factory=SAXParserFactory.newInstance();//解析器,调用适当handler
SAXParser parser=factory.newSAXParser();//将xml和DefaultHandler对象传递给解析器
URL confURL=XMLConfigParser.class.getClassLoader(类加载器).getResource(filename);
parser.parse(confURL.toString(), handler); props=handler.getProps(); }
测试:public static void main(String[] args){
DatabaseConfigParser databaseConfig=new DatabaseConfigParser();
try{ databaseConfig.parse("database.conf.xml");
Properties dbProps=databaseConfig.getProps();
System.out.println(dbProps.getProperty("driver"));
System.out.print(dbProps.getProperty("url"));}
catch(Exception e){ e.printStackTrace(); }}}
使用:import java.util.Properties;import java.sql.*;
public class Use{ private Connection conn; Properties dbProps;
public Use()throws Exception{//通过构造函数获得
DatabaseConfigParser databaseConfig=new DatabaseConfigParser();
databaseConfig.parse("database.conf.xml");
this.dbProps=databaseConfig.getProps();
public Connection getConnection()throws java.sql.SQLException{
try{ Class.forName(dbProps.getProperty(“driver”));}
catch(java.lang.ClassNotFoundException e){System.out.println(“not found”);}
return java.sql.DriverManager.getConnection(dbProps.getProperty(“url”),
dbProps.getProperty(“user”), dbProps.getProperty(“password”));}
11.利用DOM进行解析:import org.w3c.dom.*;import org.apache.xerces.parsers.DOMParser;
public class FirstDOMParser{ public static void main(String[] args) {
try {DOMParser parser = new DOMParser(); parser.parse("D:\\Lixin\\ bank.xml");
Document doc = parser.getDocument();// Document对象代表整个文档,包含所有Node对象
NodeList nodelist = doc.getElementsByTagName("client");
System.out.println(nodelist.getLength() + " <client> elements.");
nodelist = doc.getElementsByTagName("employee");//返回子孙节点nodelist对象
System.out.println(nodelist.getLength() + " <employee> elements.");
} catch (Exception e) { e.printStackTrace(System.err); } }}