Recently used in the project to read the XML configuration file connected to the database content, in. NET use XmlDocument to manage XML files, in Java can use dom4j, in fact, the principle is the same, is to find the node in the XML file, and then get the contents of the node.
XML file
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "UTF-8"?><config><db-info><driver-name> Oracle.jdbc.driver.oracledriver</driver-name><url>jdbc:oracle:thin: @localhost: 1521:orcl</url ><user-name>haha</user-name><password>haha</password></db-info></config ></span>
1. Read the XML file.
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >saxreader reader=new Saxreader (); InputStream in=thread.currentthread (). Getcontextclassloader (). getResourceAsStream ("Sys-conf.xml");D ocument doc=reader.read (in);</span>
Using the Saxreader class provided in dom4j, the XML is read and loaded into the document for parsing.
2. Get the node, read the data
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >element drivernameelt= (Element) doc.selectobject ("/config/db-info/driver-name"); Element urlelt= (Element) Doc.selectobject ("/config/db-info/url"); Element usernameelt= (Element) Doc.selectobject ("/config/db-info/user-name"); Element passwordelt= (Element) Doc.selectobject ("/config/db-info/password"); String Drivername=drivernameelt.getstringvalue (); String Url=urlelt.getstringvalue (); String Username=usernameelt.getstringvalue (); String Password=passwordelt.getstringvalue ();</span>
returns the node read in doc to element.
Summarize
dom4j is very simple to use. As long as you understand the basic Xml-dom model, you can use it. dom4j's biggest feature is the use of a large number of interfaces, which is also more "interface-oriented programming."
DOM4J Read XML file