Package com.skaringa.javaxml.example

Source Code of com.skaringa.javaxml.example.PreAndPostprocessingExample

package com.skaringa.javaxml.example;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.xml.transform.stream.StreamSource;

import com.skaringa.javaxml.ObjectTransformer;
import com.skaringa.javaxml.ObjectTransformerFactory;

/**
* Demonstrate the usage of pre- and postprocessing.
*/
public final class PreAndPostprocessingExample {

  private static final String XML_IN_RES =
    "com/skaringa/javaxml/example/Items.xml";
  private static final String XSL_PRE_RES =
    "com/skaringa/javaxml/example/PreItems.xsl";
  private static final String XSL_POST_RES =
    "com/skaringa/javaxml/example/PostItems.xsl";

  /**
   * MAIN.
   * @param args Program arguments (not used).
   */
  public static void main(String[] args) {

    try {
      // Get an ObjectTransformer.
      ObjectTransformer trans =
        ObjectTransformerFactory.getInstance().getImplementation();
      // The transformer should create extra line feeds in the output.
      trans.setProperty(javax.xml.transform.OutputKeys.INDENT, "yes");

      // set pre- and postprocessing instruction
      trans.setPreprocessorInstruction(
        new StreamSource(ClassLoader.getSystemResourceAsStream(XSL_PRE_RES)));
      trans.setPostprocessorInstruction(
        new StreamSource(ClassLoader.getSystemResourceAsStream(XSL_POST_RES)));

      // deserialize customized xml into a collection of strings
      // (using preprocessing instructions)
      Collection coll =
        (Collection) trans.deserialize(
          new StreamSource(ClassLoader.getSystemResourceAsStream(XML_IN_RES)));

      // work with the collection...
      Collection newColl = new ArrayList();
      Iterator it = coll.iterator();
      while (it.hasNext()) {
        newColl.add(firstUp((String) it.next()));
      }

      // serialize the collection into a customized xml string
      // (using postprocessing instructions)
      System.out.println(trans.serializeToString(newColl));
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Convert the first char of str to upper case.
   * @param str The string to convert.
   * @return The string with an upper case first letter.
   */
  private static String firstUp(String str) {
    try {
      StringBuffer sb = new StringBuffer(str.substring(0, 1).toUpperCase());
      sb.append(str.substring(1));
      return sb.toString();
    }
    catch (Exception e) {
      return str;
    }
  }

  /**
   * Hide ctor because this is an utility class.
   */
  private PreAndPostprocessingExample() {
  }
}
TOP

Related Classes of com.skaringa.javaxml.example.PreAndPostprocessingExample

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.