PropsToXMLpublic class PropsToXML extends Object PropsToXML takes a standard Java properties
file, and converts it into an XML format. This makes properties
like enhydra.classpath.separator "groupbable" by
"enhydra", "classpath", and by the key name, "separator", which
the standard Java java.util.Properties class does
not allow. |
Methods Summary |
---|
public void | convert(java.lang.String propertiesFilename, java.lang.String xmlFilename) This will take the supplied properties file, and
convert that file to an XML representation, which is
then output to the supplied XML document filename.
// Get Java Properties object
FileInputStream input = new FileInputStream(propertiesFilename);
Properties props = new Properties();
props.load(input);
// Convert to XML
convertToXML(props, xmlFilename);
| private void | convertToXML(java.util.Properties props, java.lang.String xmlFilename) This will handle the detail of conversion from a Java
Properties object to an XML document.
// 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 = props.propertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = (String)propertyNames.nextElement();
String propertyValue = props.getProperty(propertyName);
createXMLRepresentation(root, propertyName, propertyValue);
}
// Output document to supplied filename
XMLOutputter outputter = new XMLOutputter(" ", true);
FileOutputStream output = new FileOutputStream(xmlFilename);
outputter.output(doc, output);
| private void | createXMLRepresentation(org.jdom.Element root, java.lang.String propertyName, java.lang.String propertyValue) This will convert a single property and its value to
an XML element and textual value.
/*
Element element = new Element(propertyName);
element.setText(propertyValue);
root.addContent(element);
*/
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);
last.setAttribute("value", propertyValue);
current.addContent(last);
| public static void | main(java.lang.String[] args) Provide a static entry point for running.
if (args.length != 2) {
System.out.println("Usage: java javaxml2.PropsToXML " +
"[properties file] [XML file for output]");
System.exit(0);
}
try {
PropsToXML propsToXML = new PropsToXML();
propsToXML.convert(args[0], args[1]);
} catch (Exception e) {
e.printStackTrace();
}
|
|