开发者

XML parsing java confirmation

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:\\te开发者_Python百科st_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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜