PropsToXML takes a standard Java properties file, and converts it into an XML file : Preference Properties « Development Class « Java






PropsToXML takes a standard Java properties file, and converts it into an XML file

     


/*--

 Copyright (C) 2001 Brett McLaughlin.
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions, and the disclaimer that follows
    these conditions in the do*****entation and/or other materials
    provided with the distribution.

 3. The name "Java and XML" must not be used to endorse or promote products
    derived from this software without prior written permission.  For
    written permission, please contact brett@newInstance.com.

 In addition, we request (but do not require) that you include in the
 end-user do*****entation provided with the redistribution and/or in the
 software itself an acknowledgement equivalent to the following:
     "This product includes software developed for the
      'Java and XML' book, by Brett McLaughlin (O'Reilly & Associates)."

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED.  IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGE.

 */

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import org.jdom.Do*****ent;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

/**
 * <b><code>PropsToXML</code></b> takes a standard Java properties
 *   file, and converts it into an XML format. This makes properties
 *   like <code>enhydra.classpath.separator</code> "groupbable" by
 *   "enhydra", "classpath", and by the key name, "separator", which
 *   the standard Java <code>java.util.Properties</code> class does
 *   not allow.
 */
public class Main {

    /**
     * <p> This will take the supplied properties file, and
     *   convert that file to an XML representation, which is
     *   then output to the supplied XML do*****ent filename. </p>
     *
     * @param propertiesFilename file to read in as Java properties.
     * @param xmlFilename file to output XML representation to.
     * @throws <code>IOException</code> - when errors occur.
     */
    public void convert(String propertiesFilename, String xmlFilename)
        throws IOException {

        // Get Java Properties object
        FileInputStream input = new FileInputStream(propertiesFilename);
        Properties props = new Properties();
        props.load(input);

        // Convert to XML
        convertToXML(props, xmlFilename);
    }

    /**
     * <p> This will handle the detail of conversion from a Java
     *  <code>Properties</code> object to an XML do*****ent. </p>
     *
     * @param props <code>Properties</code> object to use as input.
     * @param xmlFilename file to output XML to.
     * @throws <code>IOException</code> - when errors occur.
     */
    private void convertToXML(Properties props, String xmlFilename)
        throws IOException {

        // Create a new JDOM Do*****ent with a root element "properties"
        Element root = new Element("properties");
        Do*****ent doc = new Do*****ent(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 do*****ent to supplied filename
        XMLOutputter outputter = new XMLOutputter("  ", true);
        FileOutputStream output = new FileOutputStream(xmlFilename);
        outputter.output(doc, output);
    }

    /**
     * <p> This will convert a single property and its value to
     *  an XML element and textual value. </p>
     *
     * @param root JDOM root <code>Element</code> to add children to.
     * @param propertyName name to base element creation on.
     * @param propertyValue value to use for property.
     */
    private void createXMLRepresentation(Element root,
                                         String propertyName,
                                         String propertyValue) {

        /*
        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);
    }

    /**
     * <p> Provide a static entry point for running. </p>
     */
    public static void main(String[] args) {
        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();
        }
    }
}

/*   Java and XML, Second Edition
 *   Solutions to Real-World Problems
 *   By Brett McLaughlin
 *   Second Edition August 2001
 *   ISBN: 0-596-00197-5
 *   http://www.oreilly.com/catalog/javaxml2/
 */

   
    
    
    
    
  








Related examples in the same category

1.Put key value pair to PreferencePut key value pair to Preference
2.Get childrenNames from PreferencesGet childrenNames from Preferences
3.Get keys from PreferencesGet keys from Preferences
4.Get name and parent from PreferenceGet name and parent from Preference
5.Get node from PreferenceGet node from Preference
6.Get value from PreferencesGet value from Preferences
7.Export Preferences to XML fileExport Preferences to XML file
8.Passing references aroundPassing references around
9.Retrieve the preference node using a Class object and saves and retrieves a preference in the node.
10.Determining If a Preference Node Contains a Specific Key
11.Determining If a Preference Node Contains a Specific Value
12.Removing a Preference from a Preference Node
13.Getting and Setting Java Type Values in a Preference
14.Getting the Maximum Size of a Preference Key and Value
15.Getting the Roots of the Preference Trees
16.Retrieving a Preference Node
17.Removing a Preference Node
18.Determining If a Preference Node Exists
19.Retrieving the Parent and Child Nodes of a Preference Node
20.Exporting the Preferences in a Preference Node
21.Exporting the Preferences in a Subtree of Preference Nodes
22.Determining When a Preference Node Is Added or Removed
23.Read / write data in Windows registry
24.Listening for Changes to Preference Values in a Preference Node
25.Saving Data with the Preferences APISaving Data with the Preferences API
26.Preference Example:: export To FilePreference Example:: export To File
27.Properties load
28.Properties TreeMap and StreamProperties TreeMap and Stream
29.Parse Properties FilesParse Properties Files
30.Preferences DemoPreferences Demo
31.Properties TestProperties Test
32.Sort Properties when saving
33.Loading configuration parameters from text file based properties
34.To read a Properties file via an Applet
35.A Properties file stored in a JAR can be loaded this way
36.Load a properties file in the startup directory
37.Have a multi-line value in a properties file
38.Convert a Properties list into a map.
39.Listing All System Properties
40.Getting and Setting Properties
41.Use XML with Properties
42.Store properties as XML file
43.Reading and Writing a Properties File
44.Read system property as an integer
45.Read a configuration file using java.util.Properties
46.Load properties from XML file
47.Here is an example of the contents of a properties file:
48.Use the Registry to store informations (Preferences API)
49.Load a properties file in the classpath
50.Listing the system properties
51.Properties Demo
52.Utility class for preferences
53.Static methods for retrieving and system properties and converting them to various types
54.Store recent items (e.g. recent file in a menu or recent search text in a search dialog)
55.Storing/loading Preferences
56.A frame that restores position and size from user preferences and updates the preferences upon exit
57.A frame that restores position and size from a properties file and updates the properties upon exitA frame that restores position and size from a properties file and updates the properties upon exit
58.A simple Properties extension easing the loading and saving of data