Whats the correct way to extend the functionality of DOM elements?
After taking quite a long break from active coding I am just starting to get accustomed to Java again, so this might be considered a "newbie question". Any help is appreciated.
Consider the following scenario. I am parsing an XML document as DOM. I am using javax.xml.parsers.DocumentBuilder
to obtain an org.w3c.dom.Document
node and scan through its org.w3c.dom.Element
nodes, and I am fine with that.
However, I would like to extend the functionality of my org.w3c.dom.Element
objects. Say, I would like to have a convenient way to extract some 开发者_如何学Cinformation from the nodes by giving them some public FancyObject toFancyObject()
method. Whats the right way of doing this?
Considering that org.w3c.dom.Element
is an interface, inheritance seems to be no option. Composition, on the other hand, seems to be quite cumbersome in this case, since this would be like 5% new functionality and 95% delegation of the existing methods.
Also, I am aware that I could always write a static
utility method to obtain my FancyObject, but I would like to avoid this solution.
You have a couple of options:
- Use the user data field of the Node interface. You can attach arbitrary objects to i t and build something that resembles your static variant.
- Use JDOM or DOM4J instead. These APIs are better suited for your requirements w.r.t. extending base implementation classes. For example, with JDOM you can define a custom NodeFactory that can create the customized Element implementations.
- Use JAXB to unmarshal the XML into an object graph. In this case, you have almost complete freedom to implement custom behavior.
精彩评论