1

this is the way i made an XML file to a Java object(s). i used "xjc" and a valid XML schema, and i got back some "generated" *.java files. i imported them into a different package in eclipse. I am reading the XML file in 2 way now.

1) Loading the XML file:

   System.out.println("Using FILE approach:");
   File f = new File ("C:\\test_XML_files\\complex.apx");
   JAXBElement felement = (JAXBElement) u.unmarshal(f);
   MyObject fmainMyObject = (MyObject) felement.getValue ();

2) Using a DOM buider:

       System.out.println("Using DOM BUILDER Approach:");
       JAXBElement element = (JAXBElement) u.unmarshal(test());;
       MyObject mainMyObject  = (MyObject ) element.getValue ();

now in method "test()" the code below is included:

public static Node test(){

   Document document = parseXmlDom();
   return document.getFirstChild();
}

private static Document parseXmlDom() {

    Document document = null;

    try {

      // getting the default implementation of DOM builder
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();

      // parsing the XML file
      document = builder.parse(new File("C:\\test_XML_files\\MyXML_FILE.apx"));

    } catch (Exception e) {
      // catching all exceptions
      System.out.println();
      System.out.println(e.toString());
    }
    return document;
}

is this the standard way of doing XML to an Java Object? I tested if I could access the object and everything works fine. (so far) Do you suggest a different approach?? or is this one sufficient?

pantelis
  • 81
  • 1
  • 2
  • 4
  • 1
    There are lots of ways to access XML. As for JAXB, check out http://download.oracle.com/javase/6/docs/api/javax/xml/bind/Unmarshaller.html -- their examples include your two approaches and more. – Vance Maverick Feb 19 '11 at 01:22
  • Are you looking for DOM objects or Java XML binding? – gigadot Feb 19 '11 at 01:43
  • Check out this great answer by Voo: http://stackoverflow.com/questions/5059224/which-is-the-best-library-for-xml-parsing-in-java/5059411#5059411 – bdoughan Feb 20 '11 at 22:24

1 Answers1

0

I don't know about a "standard way", but either way looks OK to me. The first way looks simpler ( less code ) so that's the way I'd probably do it, unless there were other factors / requirements.

FWIW, I'd expect that the unmarshal(File) method was implemented to do pretty much what you are doing in your second approach.


However, it is really up to you (and your co-workers) to make judgments about what is "sufficient" for your project.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216