Jdom reads XML files and jdom reads xml files
When learning Spring, we often see a lot of xml configuration files. Spring uses IOC (control inversion) through configuration in the configuration file to achieve code flexibility, this article introduces a method for parsing xml-Jdom.
First, download the corresponding JAR package file from the Jdom website, import it to our java project, and then compile an xml file:
<?xml version="1.0" encoding="UTF-8"?> <HD> <disk name="C"> <capacity>8G</capacity> <directories>200</directories> <files>1580</files> </disk> <disk name="D"> <capacity>10G</capacity> <directories>500</directories> <files>3000</files> </disk> </HD>
Next, we can use Jdom to read the configuration information in xml. Our java class is as follows:
Public class Jdom {public static void main (String [] args) {try {readXml ();} catch (JDOMException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} public static void readXml () throws JDOMException, IOException {SAXBuilder saxBuilder = new SAXBuilder (); Document doc = saxBuilder. build (Jdom. class. getClassLoader (). getResourceAsStream ("test. xml "); Element root = doc. getRootElement (); // get the xml root Element List <Element> list = root. getChildren ("disk"); // obtain the child under the root Element for (element: list) {String name = Element. getAttributeValue ("name"); // obtain the name value of the disk element String capacity = element. getChildText ("capacity"); // obtain the content of the disk sub-element capacity String directories = element. getChildText ("directories"); // obtain the disk sub-element directories content String files = element. getChildText ("files"); // retrieve the content of the disk sub-element files System. out. println ("disk information:"); System. out. println ("partition drive:" + name); System. out. println ("partition capacity:" + capacity); System. out. println ("number of directories:" + directories); System. out. println ("number of files:" + files); System. out. println ("-----------------------------------");}}}
There must be many ways to read XML. Here, we only want to help you understand it. If you have a better way or method, I hope you can give me some advice. Thank you.