Java XML to XML conversion

Posted on 2008-10-25
Medium Priority
Last Modified: 2013-11-18
I have an XML input in the format:
      <attr name="field1name">
      <attr name="field2name">
      <attr name="field3name">


I want to transform it to look like this:


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 :)
Question by:ChrisOz2008
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 5
LVL 16

Expert Comment

by:Bryan Butler
ID: 22805545
Xerces2 is a good way to do it.  Are you wanting specific code?  Specifically for JAXP?

Author Comment

ID: 22806426
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.
LVL 60

Expert Comment

by:Kevin Cross
ID: 22808587
The javax.xml API has a transformation portion to it.  See here for reference:

Using JDOM and XSLT

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI


Author Comment

ID: 22813001
OK I almost got there.

Here is wha tI ended up with :

    String data = [0];
    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.loadStylesheet(new InputSource(new BufferedReader(new FileReader(stylesheetname))));
    OutputMethodHandlerImpl outputMethodHandler = new OutputMethodHandlerImpl(processor);
    FileDestination dest = new FileDestination(resultFile);
    dest.getOutputStream("xml", "UTF-8");

Instead of the output going to file I need it to go out to a string or Document.
LVL 60

Expert Comment

by:Kevin Cross
ID: 22813145
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...
LVL 60

Expert Comment

by:Kevin Cross
ID: 22813186
I think you would use OutputDocumentHandler from the JClark API instead of the OutputMethodHandler to get a Document (Destination) versus a file.
LVL 60

Expert Comment

by:Kevin Cross
ID: 22813195

Author Comment

ID: 22821953
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.
LVL 60

Expert Comment

by:Kevin Cross
ID: 22822024
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)


// method you are currently using
public void setOutputMethodHandler(OutputMethodHandler handler)

Author Comment

ID: 22822867
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.

LVL 60

Accepted Solution

Kevin Cross earned 900 total points
ID: 22822991
Which comment fixed it for you - http:#22808587?

Or http:#22822024?

Just to clarify for future readers. :)

Author Comment

ID: 22823076
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();


  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("Output End");
LVL 60

Expert Comment

by:Kevin Cross
ID: 22823133
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.


Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
Many times as a report developer I've been asked to display normalized data such as three rows with values Jack, Joe, and Bob as a single comma-separated string such as 'Jack, Joe, Bob', and vice versa.  Here's how to do it. 
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
Suggested Courses
Course of the Month15 days, 6 hours left to enroll

741 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question