在 Java 应用程序中读取 XML 文件的最佳/最简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/428073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:30:51  来源:igfitidea点击:

What is the best/simplest way to read in an XML file in Java application?

javaxmlfile

提问by rmcc

Currently our Java application uses the values held within a tab delimited *.cfg file. We need to change this application so that it now uses an XML file.

目前,我们的 Java 应用程序使用制表符分隔的 *.cfg 文件中保存的值。我们需要更改此应用程序,使其现在使用 XML 文件。

What is the best/simplest library to use in order to read in values from this file?

为了从该文件中读取值,最好/最简单的库是什么?

采纳答案by Guillaume

There are of course a lot of good solutions based on what you need. If it is just configuration, you should have a look at Jakarta commons-configurationand commons-digester.

当然,根据您的需要,有很多好的解决方案。如果只是配置,你应该看看 Jakarta commons-configurationcommons-digester

You could always use the standard JDK method of getting a document :

您始终可以使用标准的 JDK 方法来获取文档:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

[...]

File file = new File("some/path");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);

回答by Sarel Botha

I've only used jdom. It's pretty easy.

我只用过 jdom。这很容易。

Go here for documentation and to download it: http://www.jdom.org/

去这里获取文档并下载它:http: //www.jdom.org/

If you have a very very large document then it's better not to read it all into memory, but use a SAX parser which calls your methods as it hits certain tags and attributes. You have to then create a state machine to deal with the incoming calls.

如果您有一个非常非常大的文档,那么最好不要将其全部读入内存,而是使用 SAX 解析器,它会在遇到某些标记和属性时调用您的方法。然后您必须创建一个状态机来处理来电。

回答by cletus

Look into JAXB.

查看JAXB

回答by ng.

The simplest by far will be Simple http://simple.sourceforge.net, you only need to annotate a single object like so

到目前为止最简单的是 Simple http://simple.sourceforge.net,您只需要像这样注释单个对象

@Root
public class Entry {

   @Attribute
   private String a
   @Attribute
   private int b;
   @Element
   private Date c;

   public String getSomething() {
      return a;
   }
} 

@Root
public class Configuration {

   @ElementList(inline=true)
   private List<Entry> entries;

   public List<Entry> getEntries() { 
      return entries;
   }
}

Then all you have to do to read the whole file is specify the location and it will parse and populate the annotated POJO's. This will do all the type conversions and validation. You can also annotate for persister callbacks if required. Reading it can be done like so.

然后,读取整个文件所需要做的就是指定位置,它将解析并填充带注释的 POJO。这将完成所有类型转换和验证。如果需要,您还可以注释持久化回调。阅读它可以这样做。

Serializer serializer = new Persister();
Configuration configuraiton = serializer.read(Configuration.class, fileLocation);

回答by James Van Huis

Is there a particular reason you have chosen XML config files? I have done XML configs in the past, and they have often turned out to be more of a headache than anything else.

您选择 XML 配置文件有什么特殊原因吗?我过去做过 XML 配置,结果证明它们比其他任何事情都更令人头疼。

I guess the real question is whether using something like the Preferences APImight work better in your situation.

我想真正的问题是在您的情况下使用Preferences API 之类的东西是否会更好。

Reasons to use the Preferences API over a roll-your-own XML solution:

在自己的 XML 解决方案上使用 Preferences API 的原因:

  • Avoids typical XML ugliness (DocumentFactory, etc), along with avoiding 3rd party libraries to provide the XML backend

  • Built in support for default values (no special handling required for missing/corrupt/invalid entries)

  • No need to sanitize values for XML storage (CDATA wrapping, etc)

  • Guaranteed status of the backing store (no need to constantly write XML out to disk)

  • Backing store is configurable (file on disk, LDAP, etc.)

  • Multi-threaded access to all preferences for free

  • 避免典型的 XML 丑陋(DocumentFactory 等),同时避免使用 3rd 方库来提供 XML 后端

  • 内置对默认值的支持(丢失/损坏/无效条目不需要特殊处理)

  • 无需清理 XML 存储的值(CDATA 包装等)

  • 后备存储的保证状态(无需不断将 XML 写入磁盘)

  • 后备存储是可配置的(磁盘上的文件、LDAP 等)

  • 多线程免费访问所有首选项

回答by tmeisenh

Depending on your application and the scope of the cfg file, a properties file might be the easiest. Sure it isn't as elegant as xml but it certainly easier.

根据您的应用程序和 cfg 文件的范围,属性文件可能是最简单的。当然它不像 xml 那样优雅,但它肯定更容易。

回答by Pierre Buyle

JAXBis simple to use and is included in Java 6 SE. With JAXB, or other XML data binding such as Simple, you don't have to handle the XML yourself, most of the work is done by the library. The basic usage is to add annotation to your existing POJO. These annotation are then used to generate an XML Schema for you data and also when reading/writing your data from/to a file.

JAXB使用简单,包含在 Java 6 SE 中。使用 JAXB 或其他 XML 数据绑定(例如 Simple),您不必自己处理 XML,大部分工作由库完成。基本用法是给你现有的 POJO 添加注解。然后,这些注释用于为您的数据生成 XML 模式,以及在从/向文件读取/写入数据时。

回答by erickson

Use java.beans.XMLDecoder, part of core Java SE since 1.4.

使用java.beans.XMLDecoder,自 1.4 以来核心 Java SE 的一部分。

XMLDecoder input = new XMLDecoder(new FileInputStream("some/path.xml"));
MyConfig config = (MyConfig) input.readObject();
input.close();

It's easy to write the configuration files by hand, or use the corresponding XMLEncoderwith some setup to write new objects at run-time.

手动编写配置文件很容易,或者使用相应XMLEncoder的一些设置在运行时编写新对象。

回答by Jonik

What is the best/simplest library to use in order to read in values from this file?

为了从该文件中读取值,最好/最简单的库是什么?

As you're asking for the simplestlibrary, I feel obliged to add an approach quite different to that in Guillaume's top-voted answer. (Of the other answers, sjbotha's JDOM mention is closest to what I suggest).

当您要求最简单的库时,我觉得有必要添加一种与Guillaume 最高投票答案中的方法完全不同的方法。(在其他答案中,sjbotha 提到的 JDOM 与我的建议最接近)。

I've come to think that for XML handling in Java, using the standard JDK tools is certainly notthe simplest way, and that only in some circumstances (such as not being able to use 3rd party libraries, for some reason) it is the best way.

我开始认为对于 Java 中的 XML 处理,使用标准的 JDK 工具肯定不是最简单的方法,并且只有在某些情况下(例如由于某种原因无法使用 3rd 方库),它才是最简单的方法。最好的办法。

Instead, consider using a good XML library, such as XOM. Here's how to read an XML file into a nu.xom.Documentobject:

相反,请考虑使用一个好的 XML 库,例如XOM。以下是将 XML 文件读入nu.xom.Document对象的方法:

import nu.xom.Builder;
import nu.xom.Document;
import java.io.File;

[...]

File file = new File("some/path");
Document document = new Builder().build(file);

So, this was just a little bit simpler, as reading the file into org.w3c.dom.Documentwasn't very complicated either, in the "pure JDK" approach. But the advantages of using a good library only start here! Whatever you're doing with your XML, you'll often get away with much simpler solutions, and less of your own code to maintain, when using a library like XOM. As examples, consider thisvs. this, or thisvs. this, or this post containing both XOM and W3C DOM examples.

所以,这只是简单一点,因为org.w3c.dom.Document在“纯 JDK”方法中,读取文件也不是很复杂。但是使用好的库的优势仅从这里开始!无论您使用 XML 做什么,在使用 XOM 之类的库时,您通常都会得到更简单的解决方案,并且需要维护的代码更少。作为示例,请考虑thisthis,或thisthis,或包含 XOM 和 W3C DOM 示例的这篇文章

Others will provide counter-arguments (like these) for why sticking to Java's standard XML APIs may be worth it - these probably have merit, at least in some cases, although personally I don't subscribe to all of them. In any case, when choosing one way or the other, it's good to be aware of both sides of the story.

其他人将提供反驳(如这些)来说明为什么坚持使用 Java 的标准 XML API 可能是值得的 - 这些可能有优点,至少在某些情况下,尽管我个人并不订阅所有这些。无论如何,在选择一种方式或另一种方式时,最好了解故事的双方。

(This answer is part of my evaluation of XOM, which is a strong contender in my quest for finding the best Java XML library to replace dom4j.)

(这个答案是我对 XOM 评估的一部分,它是我寻找替代 dom4j 的最佳 Java XML 库的有力竞争者。)

回答by Chris

Here's a really simple API that I created for reading simple XML files in Java. It's incredibly simple and easy to use. Hope it's useful for you.

这是我创建的一个非常简单的 API,用于在 Java 中读取简单的 XML 文件。它非常简单且易于使用。希望对你有用。

http://argonrain.wordpress.com/2009/10/27/000/

http://argonrain.wordpress.com/2009/10/27/000/