Generic XML utility -- in java jdom

745 Views Asked by At

Please suggest me how to do the following utility in java,

  1. Want to create the generic java class to generate the XML with JDOM.
  2. Class is capable enough to generate the any xml structure in runtime depends on parameter pass -- How?
  3. For example, In my module I need to create the XML which having 3 different child with one root i.e.

    <Child>
    
      <A>  This is normal text   </A>
    
      <B>  This is normal text  </B>
    
      <C>  This is normal text  </C>
    
    </Child>
    

  4. But in another module we required another XML file which having the 10 child with some attribute.

  5. So we decided to go for generic XML utility which generate the XML file in runtime in specific folder.
  6. Utility will help us to avoid the redundant code in the application and easy to manage as well...

Please help your friend...

Thanks Gladiator

1

There are 1 best solutions below

0
On

You can do via XStream like this:

public static String getXMLFromObject(Object toBeConverted, String classNameAlias, Map<String, String> fieldAlias,
            List<String> fieldsToBeOmitted) {
        StringBuilder objectAsXML = new StringBuilder();
        if(toBeConverted != null){
            XStream xStream = new XStream(new DomDriver());
            if(classNameAlias != null && classNameAlias != "" && classNameAlias.trim().length() > 0) {
                xStream.alias(classNameAlias, toBeConverted.getClass());
            }
            if(fieldAlias != null && !fieldAlias.isEmpty()){
                for (Entry<String, String> entry : fieldAlias.entrySet()) {
                    xStream.aliasField(entry.getKey(), toBeConverted.getClass(), entry.getValue());
                }
            }
            if(fieldsToBeOmitted != null && fieldsToBeOmitted.size() > 0){
                for (String fieldToBeOmitted : fieldsToBeOmitted) {
                    xStream.omitField(toBeConverted.getClass(), fieldToBeOmitted);
                }
            }
            objectAsXML.append(xStream.toXML(toBeConverted));
        }
        return objectAsXML.toString();
    }

If you have control over the classes which you are going to convert into XML then I would suggest to have an interface something like XMLConvertable with some structure like

public interface XMLConvertable {
    public String getClassAlias();

    public List<String> getFieldToBeOmitted();

    public Map<String, String> getFieldAliases();
}

In that case you don't need to send last three parameters in the above method just get it from the objectToBeConverted and also it makes more sense as every object in the system can declare itself whether it can be converted to XML or not.