Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Tip: Set an XSL style sheet based on XML content

Return to article.


Listing 6. Parse the document

import java.io.File;
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.Source;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class ChooseStyleSheet {
   public static void main (String args[]) {
      String rootName = null;
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         Document doc = db.parse("scores.xml");
         Element root = doc.getDocumentElement();
         rootName = root.getNodeName();
      } catch (Exception e) {
         e.printStackTrace();
      }

      try {

         TransformerFactory transformerFactory = 
                          TransformerFactory.newInstance();

         StreamSource source = new StreamSource("scores.xml");
         StreamResult result = new StreamResult("result.xml");

         String styleName = null;
         if (rootName.equals("results")){
             styleName = "scores.xsl";
         } else if (rootName.equals("entries")){
             styleName = "entries.xsl";
         }

         Transformer transformer = null;
         if (styleName == null) {

             transformer = transformerFactory.newTransformer();

         } else {

             StreamSource style = new StreamSource(styleName);
             transformer =  transformerFactory.newTransformer(style);

         }

         transformer.transform(source, result);

      } catch (Exception e) { 
		e.printStackTrace();
      }
   }
}


Return to article.