Solved

Java XML to XML conversion

Posted on 2008-10-25
13
313 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
  • 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 59

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
 

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 59

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 59

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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 59

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 59

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 59

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 59

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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Java 1603 Error 2 42
eclipse formatting 6 43
micro services spring boot application error 3 34
Java DateChooser? 2 13
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
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.
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…

762 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now