简体   繁体   English

如何使用Java读取XML文件?

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

I need to read an XML file using Java. 我需要使用Java读取XML文件。 Its contents are something like 它的内容就像

<ReadingFile>
    <csvFile>
        <fileName>C:/Input.csv</fileName>
        <delimiter>COMMA</delimiter>
        <tableFieldNamesList>COMPANYNAME|PRODUCTNAME|PRICE</tableFieldNamesList>
        <fieldProcessorDescriptorSize>20|20|20</fieldProcessorDescriptorSize>
        <fieldName>company_name|product_name|price</fieldName>
    </csvFile>
</ReadingFile>

Is there any special reader/JARs or should we read using FileInputStream ? 是否有特殊的阅读器/ JAR,还是应该使用FileInputStream进行阅读?

Check out Java's JAXP APIs which come as standard. 查看标准提供的Java JAXP API。 You can read the XML in from the file into a DOM (object model), or as SAX - a series of events (your code will receive an event for each start-of-element, end-of-element etc.). 您可以将XML从文件读入DOM(对象模型),也可以将其读为SAX-一系列事件(您的代码将为每个元素开始,元素结束等接收一个事件)。 For both DOM and SAX, I would look at an API tutorial to get started. 对于DOM和SAX,我都会看一下API入门指南。

Alternatively, you may find JDOM easier/more intuitive to use. 另外,您可能会发现JDOM使用起来更容易/更直观。

Another suggestion: Try out Commons digester. 另一个建议:尝试使用Commons消化器。 This allows you to develop parsing code very quickly using a rule-based approach. 这使您可以使用基于规则的方法非常快速地开发解析代码。 There's a tutorial here and the library is available here 有一个教程在这里和图书馆可在这里

I also agree with Brian and Alzoid in that JAXB is great to get you up and running quickly. 我也同意Brian和Alzoid的观点,因为JAXB非常适合快速启动并运行。 You can use the xjc binding compiler that ships with the JDK to auto generate your Java classes given an XML schema. 您可以使用JDK附带的xjc绑定编译器在给定XML模式的情况下自动生成Java类。

xstream would do very nicely here. xstream在这里会做得很好。 Check out the one page tutorial 查看一页教程

There are two major ways to parse XML with Java. 用Java解析XML有两种主要方法。 The first is to use a SAX parser see here 首先是使用SAX解析器, 请参见此处

which is fairly simple. 这很简单。

The second option is to use a DOM parser see here 第二个选项是使用DOM解析器, 请参见此处

which is more complicated but gives you more control. 这比较复杂,但可以提供更多控制权。

JAXB是另一种可能满足您需求的技术。

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

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