public void store(Writer writer, String header)
throws IOException {
// Create a new JDOM Document with a root element "properties"
Element root = new Element("properties");
Document doc = new Document(root);
// Get the property names
Enumeration propertyNames = propertyNames( );
while (propertyNames.hasMoreElements( )) {
String propertyName = (String)propertyNames.nextElement( );
String propertyValue = getProperty(propertyName);
createXMLRepresentation(root, propertyName, propertyValue);
}
// Output document to supplied filename
XMLOutputter outputter = new XMLOutputter(" ", true);
outputter.output(doc, writer);
}
private void createXMLRepresentation(Element root,
String propertyName,
String propertyValue) {
int split;
String name = propertyName;
Element current = root;
Element test = null;
while ((split = name.indexOf(".")) != -1) {
String subName = name.substring(0, split);
name = name.substring(split+1);
// Check for existing element
if ((test = current.getChild(subName)) == null) {
Element subElement = new Element(subName);
current.addContent(subElement);
current = subElement;
} else {
current = test;
}
}
// When out of loop, what's left is the final element's name
Element last = new Element(name);
last.setText(propertyValue);
/** Uncomment this for Attribute usage */
/*
last.setAttribute("value", propertyValue);
*/
current.addContent(last);
}
Not much needs comment. There are a few lines of code highlighted to
illustrate some changes, though. The first two changes ensure that
the superclass is used to obtain the property names and values,
rather than the Properties object that was passed
into the version of this method in PropsToXML. The
third change moves from using a string filename to the supplied
Writer for output. With those few modifications,
you're all set to compile the XMLProperties
source file.