文件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;
}
}
闽公网安备 35060202000074号