19 ก.ค. 2554

Xml to Html

แปลง  xml เป็น html

ไฟล์ hello.xsl

<xsl:stylesheet version = '1.0'
     xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match="h1">
       <h1>
      <center>
     <xsl:value-of select="."/>
               </center>
            </h1>
</xsl:template>
<xsl:template match="bold">
     <table align="center" border="1">
       <tr>
    <xsl:for-each select=".">
       <td>
        <xsl:value-of select="."/>
       </td>
    </xsl:for-each>
            </tr>
     </table>
</xsl:template>
<xsl:template match="red">
<table align="center" border="1">
      <tr>
   <td>
     <p style="color:red">
    <xsl:value-of select="."/>
     </p>
   </td>
        </tr>  
     </table>
</xsl:template>
<xsl:template match="italic">
<table align="center" border="1">
      <tr>
   <td>
    <p>
     <xsl:value-of select="."/>
    </p>
            </td>
        </tr>
          
     </table>
</xsl:template>
</xsl:stylesheet> 

hello.xml


<?xml version="1.0"?>

<source>

<h1>TEST XSLT FOR CREATE WEB SITE BY WONGSAKORN</h1>

<bold>Hello1, world.</bold>

<bold>Hello2, world.</bold>

<bold>Hello3, world.</bold>

<bold>Hello4, world.</bold>

<bold>Hello5, world.</bold>

<red>I am </red>

<italic>fine.</italic>

</source>


SimpleTransformHtml.java 

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JOptionPane;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class SimpleTransformHtml
{
 public static void main(String[] args)
    throws TransformerException, TransformerConfigurationException, 
           FileNotFoundException, IOException{  
 TransformerFactory tFactory = TransformerFactory.newInstance();
 String sourceFile = "hello";
 String html = ".html";
 Transformer transformer = tFactory.newTransformer(new StreamSource(sourceFile+xsl));
 transformer.transform(new StreamSource(sourceFile+xml), new StreamResult(new FileOutputStream(sourceFile+html)));
 System.out.println("************* The result is in "+sourceFile+html+" *************");
 Runtime.getRuntime().exec
   ("rundll32 SHELL32.DLL,ShellExec_RunDLL " + sourceFile+html);
  }
}


จะได้ตามด้านล้างนี้

TEST XSLT FOR CREATE WEB SITE BY WONGSAKORN

Hello1, world.
Hello2, world.
Hello3, world.
Hello4, world.
Hello5, world.
I am
fine.

ไม่มีความคิดเห็น:

แสดงความคิดเห็น