I've just written a course for posting data from an xml file to some database using dom4j. It endend as a number of xpath claims covered with java, - and delay pills work, however i strongly believe that there's an easy method to do this.

What's the preferred method to import data from xml right into a db?

Based on what type of XML you've, JAXB (the industry standard a part of Java SE since 1.6) may be the most simple way to cope with it. Simply make a category much like your XML structure, make the setters and getters for that fields along with a @XmlRootElement annotation to the top class. Then something similar to

Unmarshaller um = JAXBContext.newInstance(YourClass.class).createUnmarshaller();
YourClass input = (YourClass) um.unmarshal(new FileReader("file.xml"));

like magic converts your XML file to some Java object. Then it ought to be simple to email the DB of your liking.

I've discovered Simple very simple to use for creating Java objects from XML. We make use of this to create default configuration that people may then store using Hibernate.

I frequently had exactly the same problem, and desire I'd exactly the same tools ten years ago which i do now.

If you want to read existing XML into normal Java classes, Personally, i think that apache digester is a lot more elegant and simpler to make use of than dom4j, because you just specify the mapping.

Then, use Hibernate to create the types of materials lower towards the database.

It truly is dependent around the format of the XML file. Are you able to elaborate further?

During my situation, I've a credit card applicatoin that the simple Key->Value pair syntax saved in XML, by which I personally use DOM to iterate within the nodes and generate SQL to place the information.

using XPath to get this done will be a perfectly fine solution

You will find several questions you need to request yourself prior to trying other things:

  • could it be worth cleaning? In the event that application won't be utilized a lot more than rarely, "don't fix what ain't damaged".
  • will it get transformed frequently? For the reason that situation, easy maintenance and readability are vital, and dom4j is most likely pretty good on that.
  • is performance associated with a importance? If it doesn't make a difference your application runs in 50 % of time, return to the prior bullet: "better" is only going to mean neater for the reason that situation.

It certainly is dependent on exactly your work. I suppose you attempting to extract data from inside XML documents. If that's the case, xpath may go ok, however i personally still like data binding more: read XML, bind to java objects, get data via regular Bean/POJO accessors. Or even better, if using ORM, bind to/from objects ORM (like hibernate) may use.

For datd binding I'd election for JAXB, or XStream. I'd ony use any DOM alternative if xpath was adopted.