Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse XML into DOM tree with custom object implementations in Java

I want to parse an XML document into a DOM tree in Java such that certain objects (e.g. instances of org.w3c.dom.Node or org.w3c.dom.Element) in the tree can be downcast to instances of classes that I have created, while minimizing the amount of XML-related code that I need to (re)implement. As a (very simple) example, if I have an XML element like:

<Vector size="5">
  1.0 -1.0 3.0 -2.73e2
</Vector>

I would like to customize the parser to instantiate the following for it:

public class Vector extends /* some parser class */ {
  private double[] elements;

  /* constructors; etc.*/

  public double dotProduct(Vector v) {
    /* implementation */
  }
}

such that I can pass instances of Vector created by the parser to, for example, javax.xml.xpath objects' methods and have them work correctly. What is the quickest way to achieve this? Is it possible with Java SE alone, or are third-party libraries (e.g. Xerces) necessary?

like image 525
TechnocratiK Avatar asked Nov 13 '22 05:11

TechnocratiK


1 Answers

I'm not sure what your requirements are, but assuming you're in control of what the XML looks like, what I would use is XStream. It will allow you to skip all the DOM manipulation completely.

Now from their 2 minute tutorial, it may not seem like it's built for this use case, but it actually is. You create your java classes first, make sure they generate the XML the way you want it to look, and then use it to read your already existing XML back into your program as XStream objects. It's a very pleasant library to use.

like image 151
Daniel Kaplan Avatar answered Nov 14 '22 23:11

Daniel Kaplan