DOM4J Read XML file

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.