您的位置:首页 > 数据库

Java、XML与数据库编程实践(二)

2008-05-01 05:38 423 查看
文件DbXMLParser.Java封装了对XML文件的操作。

import Javax.XML.parsers.*;
import org.w3c.dom.*;
import org.XML.sax.*;
import Java.io.*;
public class DbXMLParser
{
static String XMLfile;
public DbXMLParser(String filename)
{
XMLfile=filename;
}
public static Element loadDocument()
{
try
{
//工厂
DocumentBuilderFactory dcfactory=DocumentBuilderFactory.newInstance();
//文档构造器
DocumentBuilder db=dcfactory.newDocumentBuilder();
//构造的文档
Document doc=db.parse(XMLfile);
//根元素
Element root=doc.getDocumentElement();

return root;
}catch( ParserConfigurationException e){
System.out.println("ParserConfigurationException");
e.printStackTrace();
}catch(IOException e) {
System.out.println("IOException ");
e.printStackTrace();
}catch(SAXException e) {
System.out.println("SAXException ");
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
public ConnPara getSource()
{
Element root=loadDocument();
if( root==null) { return null; }
NodeList nodes=root.getElementsByTagName("source");
if(nodes.getLength()>0)
{
Node node=nodes.item(0);
String connclass=getChildElementValue(node,"class");
String url=getChildElementValue(node,"url");
String username=getChildElementValue(node,"user");

String password=getChildElementValue(node,"password");
return new ConnPara(connclass,url,username,password);
}
return null;
}
public ConnPara getDest()
{
Element root=loadDocument();
if( root==null) return null;
NodeList nodes=root.getElementsByTagName("dest");
if(nodes.getLength()>0)
{
Node node=nodes.item(0);
String connclass=getChildElementValue(node,"class");
String url=getChildElementValue(node,"url");
String username=getChildElementValue(node,"user");
String password=getChildElementValue(node,"password");
return new ConnPara(connclass,url,username,password);
}
return null;
}
//得到子元素的值
private String getChildElementValue(Node node,String subTagName)

{
String returnString = "";
if(node != null)
{
NodeList children = node.getChildNodes();
for(int innerLoop = 0; innerLoop < children.getLength(); innerLoop++)
{
Node child = children.item(innerLoop);
if(child == null || child.getNodeName() == null || !child.getNodeName().equals(subTagName))
continue;
Node grandChild = child.getFirstChild();
if(grandChild.getNodeValue() != null)
return grandChild.getNodeValue();
}
}
return returnString;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: