Java, XML and Database Programming Practice (2)

zhaozj2021-02-16  49

Document DBXMLPARSER.JAVA encapsulates the operation of the XML file.

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 loadingdocument ()

{

Try

{

//factory

DocumentBuilderFactory dcfactory = documentbuilderfactory.newinstance ();

// Document constructor

DocumentBuilder DB = dcfactory.NewDocumentBuilder ();

// Context document

Document doc = db.parse (XMLFile);

/ Root elements

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 = loadingDocument ();

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 = loadingDocument ();

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;

}

// Get the value of the child element

Private string getChildElementValue (Node Node, String Subtagname)

{

String Returnstring = ""

IF (Node! = NULL)

{

Nodelist children = node.getchildnodes ();

For (int innerloop = 0; 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;

}

}

转载请注明原文地址:https://www.9cbs.com/read-24428.html

New Post(0)