Solved

Java XML to XML conversion

Posted on 2008-10-25
13
326 Views
Last Modified: 2013-11-18
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 :)
0
Comment
Question by:ChrisOz2008
[X]
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
13 Comments
 
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?
0
 

Author Comment

by:ChrisOz2008
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.
0
 
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
http://www.ibm.com/developerworks/java/library/x-tipjdom.html

0
Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

 

Author Comment

by:ChrisOz2008
ID: 22813001
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.
0
 
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...
0
 
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.
http://www.cs.helsinki.fi/group/xmltools/formatters/xt/xt-20020426a-src/doc/api/com/jclark/xsl/sax/package-summary.html
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 22813195
0
 

Author Comment

by:ChrisOz2008
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.
0
 
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)

vs

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

Author Comment

by:ChrisOz2008
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.

0
 
LVL 60

Accepted Solution

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

Or http:#22822024?

Just to clarify for future readers. :)
0
 

Author Comment

by:ChrisOz2008
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();

    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");
  }
}
0
 
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.

/kev
0

Featured Post

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

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. 
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
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 learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

728 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