Need to introduce a third-party jar package: dom4j
Package Test;import Java.io.file;import java.io.ioexception;import java.util.iterator;import org.dom4j.Attribute; Import Org.dom4j.document;import Org.dom4j.documentexception;import Org.dom4j.element;import Org.dom4j.io.saxreader;public class Test {public static void main (string[] args) {Saxreader reader = new Saxre Ader (); String realpathstring; try {//Get the file true path realpathstring = new File (""). Getcanonicalpath () + "/dbconfig.xml"; System.out.println ("[Path:]" + realpathstring); Read File Document document = Reader.read (realpathstring); Get the components root node Element components = Document.getrootelement (); Traverse component Element component; for (Iterator i = components.elementiterator ("component"); I.hasnext ();) {component = (Element) i.next (); Gets the Name property Attribute name = Component.attribute ("name"); System.out.println ("[Name:]" + name.gettext ()); Gets the class attribute Attribute cls = Component.attribute ("class"); System.out.println ("[Class:]" + cls.gettext ()); Iterates through all the properties of the current component for (Iterator ite = Component.elementiterator ("property"); Ite.hasnext ();) {Element property = (Element) Ite.next (); Gets the property's name attribute and the value Attribute pname = Property.attribute ("name"); System.out.println ("[" + pname.gettext () + "]:" + property.gettext (). Trim ()); }}} catch (IOException | Documentexception e) {e.printstacktrace (); } }}
Dbconfig.xml
<?xml version= "1.0" encoding= "UTF-8"?><components> <component name= "DataSource" class= "test. Xdatasource "> <property name=" Driverclassname ">" Com.mysql.jdbc.Driver "</property> < Property name= "URL" > "jdbc:mysql://127.0.0.1:3306/mytestdb" </property> <property name= " User > Root </property> <property name= "password" > "" </property> </component> </components>
Java Read XML file