简体   繁体   中英

How to read an XML file with Java?

I don't need to read complex XML files. I just want to read the following configuration file with a simplest XML reader

<config>
    <db-host>localhost</db-host>
    <db-port>3306</db-port>
    <db-username>root</db-username>
    <db-password>root</db-password>
    <db-name>cash</db-name>
</config>

How to read the above XML file with a XML reader through Java?

I like jdom:

SAXBuilder parser = new SAXBuilder();
Document docConfig = parser.build("config.xml");
Element elConfig = docConfig.getRootElement();
String host = elConfig.getChildText("host");

Since you want to parse config files, I think commons-configuration would be the best solution.

Commons Configuration provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources (including XML)

You could use a simple DOM parser to read the xml representation.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse("config.xml");

If you just need a simple solution that's included with the Java SDK (since 5.0), check out the XPath package. I'm sure others perform better, but this was all I needed. Here's an example:

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;

...

try {
    XPath xpath = XPathFactory.newInstance().newXPath();
    InputSource inputSource = new InputSource("strings.xml");

    // result will equal "Save My Changes" (see XML below)
    String result = xpath.evaluate("//string", inputSource);
}
catch(XPathExpressionException e) {
    // do something
}

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="saveLabel">Save My Changes</string>
</resources>

There are several XML parsers for Java. One I've used and found particularly developer friendly is JDOM . And by developer friendly, I mean "java oriented" (ie, you work with objects in your program), instead of "document oriented", as some other tools are.

I would recommend Commons Digester , which allows you to parse a file without writing reams of code. It uses a series of rules to determine what action is should perform when encountering a given element or attribute (a typical rule might be to create a particular business object).

For a similar use case in my application I used JaxB. With Jaxb, reading XML files is like interacting with Java POJOs. But to use JAXB you need to have the xsd for this xml file. You can look for more info here

如果您希望能够直接读取和写入XML对象,则可以使用XStream

Although I have not tried XPath yet as it has just come to my attention now, I have tried a few solutions and have not found anything that works for this scenario.

I decided to make a library that fulfills this need as long as you are working under the assumptions mentioned in the readme. It has the advantage that it uses SAX to parse the entire file and return it to the user in the form of a map so you can lookup values as key -> value.

https://github.com/daaso-consultancy/ConciseXMLParser

If something is missing kindly inform me of the missing item as I only develop it based on the needs of others and myself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM