Link to home
Start Free TrialLog in
Avatar of ChrisOz2008
ChrisOz2008Flag for Australia

asked on

Java XML to XML conversion

I have an XML input in the format:
--------------------------------------------------------------
<data>
      <attr name="field1name">
            <value>90</value>
      </attr>
      <attr name="field2name">
            <value>xxxxx</value>
      </attr>
      <attr name="field3name">
            <value>1234</value>
      </attr>
</data>

--------------------------

I want to transform it to look like this:

<data>
      <fieldname1>90</filedname1>
      <fieldname2>xxxxx</filedname2>
      <fieldname3>1234</filedname3>
</data>

I can make an XSL/XSLT using my XML editor, but what is the simpest and most lightweight method to perform this transformation?  My app mainly uses jclark and javax libs.

Thanks for any advice :)
Avatar of Bryan Butler
Bryan Butler
Flag of United States of America image

Xerces2 is a good way to do it.  Are you wanting specific code?  Specifically for JAXP?
Avatar of ChrisOz2008

ASKER

Looking for something more specific, don't really have the time study all the Xerces docs right now as this is a tiny portion of my project.
Avatar of Kevin Cross
The javax.xml API has a transformation portion to it.  See here for reference:

Using JDOM and XSLT
http://www.ibm.com/developerworks/java/library/x-tipjdom.html

OK I almost got there.

Here is wha tI ended up with :

    String data = [0];
    System.out.println(data);
    String stylesheetname = "c:\\temp\\ant\\test5\\xml\\test.xsl";
    File stylesheetFile = new File(stylesheetname);
    String resultFile = "c:\\temp\\ant\\test5\\xml\\testout2.xml";
    Parser parser = createParser();
    XSLProcessor processor = new XSLProcessorImpl();
    processor.setParser(parser);
    processor.loadStylesheet(new InputSource(new BufferedReader(new FileReader(stylesheetname))));
    OutputMethodHandlerImpl outputMethodHandler = new OutputMethodHandlerImpl(processor);
    processor.setOutputMethodHandler(outputMethodHandler);
    FileDestination dest = new FileDestination(resultFile);
    dest.getOutputStream("xml", "UTF-8");
    outputMethodHandler.setDestination(dest);
    processor.parse(str2InputSource(data));

Instead of the output going to file I need it to go out to a string or Document.
Did you see the Xalan J information from IBM site I linked too?  It outputs to an XML Document object?

I will take a look at what you have...
I think you would use OutputDocumentHandler from the JClark API instead of the OutputMethodHandler to get a Document (Destination) versus a file.
http://www.cs.helsinki.fi/group/xmltools/formatters/xt/xt-20020426a-src/doc/api/com/jclark/xsl/sax/package-summary.html
I looked at this method and it requires  parser as a parameter, not sure how that gets me an output of a Document object.

Sorry I'm very dumb at XML stuff.  I'm surprised this is not a more common thing peiple want to do, read some xml in from a data stream, transform it using an XSL and output as a new data stream... what do other people do? Output it to a file?  But that seems very inefficient.. if I have a servlet for example and I have an incoming XML post which is some odd format, I transform it then process it. If i have to transform it out to file then read the file back before using my shiney newly structured XML that seems very inefficient.

Can anyone answer this question fully? 300 point to anyone that can.
Well it was answered above using JDOM and XSLT (Xalan); however, you are trying to use JClark.  Hopefully someone else knows how to better explain JClark way as I am not as familiar with that.  According to the API though, you use the org.xml.sax.DocumentHandler which serializes to a Destination object which it is using to represent generic XML Document from my reading.  More detail than that is beyond me, sorry.  Not sure if this is what you are referring to as taking parser, but this is what I was pointing to.

public void setDocumentHandler(org.xml.sax.DocumentHandler handler)

vs

// method you are currently using
public void setOutputMethodHandler(OutputMethodHandler handler)
Aaaah :)   Suddenly my mind has clicked over and I can see what you're trying to tell me. I got it sorted now in about 5 lines of code. Thanks so much for persisting with my brain failure :)

I forgot to up my point assignment in my last response so I have done so here, if you reply me back I'll accept it.

ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The last one. I had focussed on th JDOM reference which I had used before and found to be not quite what  iwas after. After you mentioned Xalan again I googled and found a really nice sample. My XML tool XMLBluePrint can take th input XML and the output I want and create me an XSL so even an XML dubass like me can get things working.

Thanks again for your advice!

Here is what I ended up with :

import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;

import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class XmlToXmlConvertor
{
   private TransformerFactory tFactory;
   private Transformer transformer;
   String stylesheetname = "c:\\temp\\ant\\test5\\xml\\test.xsl";
   String inFile = "c:\\temp\\ant\\test5\\xml\\in.xml";

  public static void main(String[] args) throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException
  {
    // Use the static TransformerFactory.newInstance() method to instantiate a TransformerFactory. The javax.xml.transform.TransformerFactory
    // system property setting determines the actual class to instantiate -- org.apache.xalan.transformer.TransformerImpl.

    XmlToXmlConvertor xmlToXmlConversion = new XmlToXmlConvertor();

    xmlToXmlConversion.performTransformation();
  }

  public void performTransformation() throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException
  {
    tFactory = TransformerFactory.newInstance();
    StringOutputStream sos = new StringOutputStream();

    // Use the TransformerFactory to instantiate a Transformer that will work with the stylesheet you specify. This method call also processes the stylesheet into
   // a compiled Templates object.

    transformer = tFactory.newTransformer(new StreamSource(stylesheetname));
    transformer.transform(new StreamSource(inFile), new StreamResult(sos));
    System.out.println("Output Start");
    System.out.println(sos);
    System.out.println("Output End");
  }
}
Very nice!
Thanks for your patience.  You thanked me for sticking with you, but you stuck with me too and hopefully got a good working solution out of it.

Happy coding.

/kev