简体   繁体   中英

Parsing a xml file using Java

I need to parse a xml file using JAVA and have to create a bean out of that xml file after parsing .

I need this while using Spring JMS in which producer is producing a xml file .First I need to read the xml file and take action according .

I read some thing about parsing and come with these option

  1. xpath
  2. DOM

Which ll be the best option to parse the xml file.

你检查JAXB了吗

There's three ways of parsing an XML file, SAX, DOM and StAX.

DOM will parse the whole file and build up a tree in memory - great for small files but obviously if this is huge then you don't want the entire tree just sitting in memory! SAX is event based - it doesn't load anything into memory per-se but just fires off a series of events as it reads through the file. StAX is a median between the two, the application moves the cursor forward as it needs, grabbing the data as it goes (so no event firing or huge memory consumption.)

What one you use will really depend on your application - all have built in libraries since Java 6.

如果需要创建对象,只需提取所需的属性并继续...我建议使用StaX,有关更多信息,请参见本教程

Looks like, you receive a serialized object via Java messaging. Have a look first, how the object is being serialized. Usually this is done with a library (jaxb, axis, ...) and you could use the very same library to create a deserializer.

You will need:

  1. The xml schema (a xsd file)
  2. The Java bean class (very helpful, it should exist)

Then, usually the library will create all helper classes and files and you don't have to care about parsing.

Umh..there are several ways you can parse an xml document to into memory and work with it. You mentioned DOM. DOM actually holds uploads the whole document into memory and then allows you to move between different branches of the XML document.

On the other hand, you could use StAX. It works similar to DOM. The only difference is that, it streams the content of the XML document thus allowing better allocation of memory. On the other hand, it does not retain the information that has already been read.

Look at : http://download.oracle.com/javaee/5/tutorial/doc/bnbem.html It gives details about both parsing methods and example code. Hope that helps.

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