简体   繁体   English

如何用Java读取XML文件?

[英]How to read an XML file with Java?

I don't need to read complex XML files. 我不需要阅读复杂的XML文件。 I just want to read the following configuration file with a simplest XML reader 我只想用最简单的XML阅读器阅读以下配置文件

<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? 如何通过Java使用XML阅读器阅读上述XML文件?

I like jdom: 我喜欢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是最好的解决方案。

Commons Configuration provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources (including XML) Commons Configuration提供了一个通用配置接口,使Java应用程序能够从各种源(包括XML)读取配置数据

You could use a simple DOM parser to read the xml representation. 您可以使用简单的DOM解析器来读取xml表示。

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. 如果您只需要一个Java SDK附带的简单解决方案(自5.0起),请查看XPath包。 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 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. Java有几种XML解析器。 One I've used and found particularly developer friendly is JDOM . 我使用过的,特别是开发人员友好的是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. 通过开发人员友好,我的意思是“面向Java”(即,您使用程序中的对象),而不是“面向文档”,就像其他一些工具一样。

I would recommend Commons Digester , which allows you to parse a file without writing reams of code. 我建议使用Commons Digester ,它允许你解析文件而不需要编写大量的代码。 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. 对于我的应用程序中的类似用例,我使用了JaxB。 With Jaxb, reading XML files is like interacting with Java POJOs. 使用Jaxb,读取XML文件就像与Java POJO交互一样。 But to use JAXB you need to have the xsd for this xml file. 但要使用JAXB,您需要为此xml文件提供xsd。 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. 虽然我还没有尝试过XPath,因为它现在刚刚引起我的注意,我已经尝试了一些解决方案并且没有找到适用于这种情况的任何东西。

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. 它的优点是它使用SAX来解析整个文件并以地图的形式将其返回给用户,因此您可以将值查找为键 - >值。

https://github.com/daaso-consultancy/ConciseXMLParser 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. 如果缺少某些东西,请告诉我缺失的项目,因为我只根据他人和我自己的需求进行开发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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