O'Reilly logo

Java and XML, Second Edition by Brett McLaughlin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

JDOM and Factories

Moving right along, recall the discussion from the last chapter on JDOM and factories. I mentioned that you would never see code like this (at least with the current versions) in JDOM applications:

// This code does not work!!
JDOMFactory factory = new JDOMFactory( );
factory.setDocumentClass("javaxml2.BrettsDocumentClass");
factory.setElementClass("javaxml2.BrettsElementClass");

Element rootElement = JDOMFactory.createElement("root");
Document document = JDOMFactory.createDocument(rootElement);

Well, that remains true. However, I glossed over some pretty important aspects of that discussion, and want to pick it up again here. As I mentioned in Chapter 7, being able to have some form of factories allows greater flexibility in how your XML is modeled in Java. Take a look at the simple subclass of JDOM’s Element class shown in Example 8-1.

Example 8-1. Subclassing the JDOM Element class

package javaxml2;

import org.jdom.Element;
import org.jdom.Namespace;

public class ORAElement extends Element {

    private static final Namespace ORA_NAMESPACE =
        Namespace.getNamespace("ora", "http://www.oreilly.com");

    public ORAElement(String name) {
        super(name, ORA_NAMESPACE);
    }

    public ORAElement(String name, Namespace ns) {
        super(name, ORA_NAMESPACE);
    }

    public ORAElement(String name, String uri) {
        super(name, ORA_NAMESPACE);
    }

    public ORAElement(String name, String prefix, String uri) {
        super(name, ORA_NAMESPACE);
    }
}

This is about as simple a subclass as you could come up with; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required