XML transformation : Transform « XML « Java






XML transformation

     

/* phonebook.xml



<PHONEBOOK>
<PERSON>
 <NAME>Joe Wang</NAME>
 <EMAIL>joe@yourserver.com</EMAIL>
 <TELEPHONE>202-999-9999</TELEPHONE>
 <WEB>www.java2s.com</WEB>
</PERSON>
<PERSON>
 <NAME>Karol</name>
 <EMAIL>karol@yourserver.com</EMAIL>
 <TELEPHONE>306-999-9999</TELEPHONE>
 <WEB>www.java2s.com</WEB>
</PERSON>
<PERSON>
 <NAME>Green</NAME>
 <EMAIL>green@yourserver.com</EMAIL>
 <TELEPHONE>202-414-9999</TELEPHONE>
 <WEB>www.java2s.com</WEB>
</PERSON>
</PHONEBOOK>


<!-- directory.xsl -->


<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">

<html>
<head>
<title>Directory</title>
</head>
<body>

<table border="1">

<tr>
 <th>Name</th>
 <th>Telephone</th>
 <th>Email</th>
</tr>

<xsl:for-each select="PHONEBOOK/PERSON">
 <xsl:sort/>
 <tr>
  <td><xsl:value-of select="NAME"/></td>
  <td><xsl:value-of select="TELEPHONE"/></td>
  <td><xsl:value-of select="EMAIL"/></td>
 </tr>
</xsl:for-each>

</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

*/

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

public class XMLTransform {

  public static void main(String args[]) {

    if (args.length != 2) {
      System.err.println("Usage: java XMLTransform xmlfile.xml stylesheet.xsl");
      System.exit(-1);
    }

    try {
      StreamSource source = new StreamSource(args[0]);
      StreamSource stylesource = new StreamSource(args[1]);

      TransformerFactory factory = TransformerFactory.newInstance();
      Transformer transformer = factory.newTransformer(stylesource);

      StreamResult result = new StreamResult(System.out);
      transformer.transform(source, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

           
         
    
    
    
    
  








Related examples in the same category

1.A Program That Performs XML Transformations
2.XSLT I18N
3.Use the transform.TransformerFactory plugability in the JAXP API
4.Processing XML Documents Partially
5.Set the TransformerFactory system property to generate and use translets
6.Transforming DOM Node to HTML with JAXP
7.Transformer with parameters
8.Create an XML file and attach an XSL
9.Applying XSLT Stylesheets
10.Catch TransformerException
11.Formatting an XML file using Transformer
12.Transforming an XML File with XSL into a DOM Document
13.XML input, output and transform utilities
14.XSL transformations: It applies a transformation to a set of employee recordsXSL transformations: It applies a transformation to a set of employee records
15.How to write an XML file. It saves a file describing a modern drawing in SVG format.
16.Applies a stylesheet to a given xml document.
17.Applies a stylesheet (that receives parameters) to a given xml document.
18.Apply some indentiation to some XML.