利用sax和xslt转换csv文件内容

package jaxp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.AttributesImpl;

public class SAX_XSL {
	
	public static void main(String[] args) throws Exception{
		transform_by_saxsource();
		transform_by_saxtransformfactory();
	}


	private static void transform_by_saxtransformfactory() throws TransformerFactoryConfigurationError, TransformerConfigurationException, IOException, SAXException {
		TransformerFactory factory = TransformerFactory.newInstance();
		if(factory.getFeature(SAXTransformerFactory.FEATURE)){
			SAXTransformerFactory saxfactory = (SAXTransformerFactory) factory;
			TransformerHandler handler = saxfactory.newTransformerHandler(new StreamSource(loadxsl()));
			handler.setResult(new StreamResult(System.out));
			CSVParser parser = new CSVParser();
			parser.setContentHandler(handler);
			System.out.println("//------------华丽的分割线----------------//");
			parser.parse(new InputSource(loadcsv()));
		}
	}


	private static void transform_by_saxsource() throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException {
		TransformerFactory factory = TransformerFactory.newInstance();
		Templates templates=  factory.newTemplates(new StreamSource(loadxsl()));
		Transformer transformer = templates.newTransformer();
		
		Source source = new SAXSource(new CSVParser(),new InputSource(loadcsv()));
		Result result = new StreamResult(System.out);
		transformer.transform(source, result);
		
	}


	private static InputStream loadxsl() {
		InputStream xsl = SAX_XSL.class.getClassLoader().getResourceAsStream("jaxp/csv.xsl");
		return xsl;
	}
	
	private static InputStream loadcsv() {
		InputStream xsl = SAX_XSL.class.getClassLoader().getResourceAsStream("jaxp/book.csv");
		return xsl;
	}
	
	public static class CSVParser implements XMLReader {
		private static final Attributes EMPTY_ATTRS = new AttributesImpl();
		private static final String HTTP_XML_ORG_SAX_FEATURES_NAMESPACES="http://xml.org/sax/features/namespaces";
		private ContentHandler contentHandler;
		private DTDHandler dtdHandler;
		private EntityResolver entityResolver;
		private ErrorHandler errorhandler;
		
		private Map featureMap = new HashMap();
		private Map propertyMap = new HashMap();
		
		public CSVParser() {
			featureMap.put(HTTP_XML_ORG_SAX_FEATURES_NAMESPACES, new Boolean(true));
		}

		public ContentHandler getContentHandler() {
			return this.contentHandler;
		}

		public void setContentHandler(ContentHandler contenthandler) {
			this.contentHandler = contenthandler;
		}
		
		public DTDHandler getDTDHandler() {
			return this.getDTDHandler();
		}

		public void setDTDHandler(DTDHandler dtdhandler) {
			this.dtdHandler = dtdhandler;
		}
		
		public EntityResolver getEntityResolver() {
			return this.entityResolver;
		}
		
		public void setEntityResolver(EntityResolver entityresolver) {
			this.entityResolver = entityresolver;
		}

		public ErrorHandler getErrorHandler() {
			return this.errorhandler;
		}

		public void setErrorHandler(ErrorHandler errorhandler) {
			this.errorhandler = errorhandler;
		}
		
		public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
			Boolean value = (Boolean) featureMap.get(name);
			if(value == null){
				return false;
			}
			return value.booleanValue();
		}

		public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
			this.featureMap.put(name, new Boolean(value));			
		}
		
		public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
			propertyMap.put(name, value);
		}
		
		public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
			return propertyMap.get(name);
		}

		public void parse(String systemId) throws IOException, SAXException {
			parse(new InputSource(systemId));			
		}
		
		private boolean requiredNameSpace() throws SAXException {
			return getFeature(HTTP_XML_ORG_SAX_FEATURES_NAMESPACES);
		}
		
		public void parse(InputSource inputsource) throws IOException, SAXException {
			ContentHandler handler = getContentHandler();
			if(handler == null){
				return;
			}
			BufferedReader reader = null;
			if(inputsource.getCharacterStream()!=null){
				reader = new BufferedReader(inputsource.getCharacterStream());
			} else if (inputsource.getByteStream()!=null){
				reader = new BufferedReader(new InputStreamReader(inputsource.getByteStream()));
			} else if (inputsource.getSystemId() !=null && inputsource.getSystemId().trim().length()>0){
				URL url = new URL(inputsource.getSystemId());
				reader = new BufferedReader(new InputStreamReader(url.openStream()));
			}
			if(reader == null){
				throw new SAXException("invalid inputsource object");
			}
			handler.startDocument();
			if(requiredNameSpace()){
				handler.startElement("", "books", "books", EMPTY_ATTRS);
			} else {
				handler.startElement("", "", "books", EMPTY_ATTRS);
			}
			
			String line = null;
			while((line = reader.readLine())!=null){
				handler.startElement("", "book", "book", EMPTY_ATTRS);
				String[] values = line.split(",");
				if(values!=null && values.length>0){
					handler.startElement("", "name", "name", EMPTY_ATTRS);
					handler.characters(values[0].toCharArray(), 0, values[0].length());
					handler.endElement("", "name", "name");
					if(values.length>=2){
						handler.startElement("", "authors", "authors", EMPTY_ATTRS);
						handler.startElement("", "author", "author", EMPTY_ATTRS);
						handler.characters(values[1].toCharArray(), 0, values[1].length());
						handler.endElement("", "author", "author");
						handler.endElement("", "authors", "authors");
					}
				}
				handler.endElement("", "book", "book");
			}
			if(requiredNameSpace()){
				handler.endElement("", "books", "books");
			} else {
				handler.endElement("", "", "books");
			}
			handler.endDocument();
		}
	}
}

 

book.csv:

java & xml,dava
java xslt,martin
hibernate in action,gavin king
spring in action,test

 csv.xsl:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
	
	<xsl:template match="/">
		<html>
		<head>
			<title>books</title>
		</head>
		<body>
		<xsl:apply-templates/>
		</body>
		</html>
	</xsl:template>
	
	<xsl:template match="books">
		<table border="1">
			<tr>
				<td>no</td>
				<td>book name</td>
				<td>authors</td>
			</tr>
			<xsl:apply-templates select="book">
				<xsl:sort order="desending" data-type="text" select="name"/>
			</xsl:apply-templates>
		</table>
	</xsl:template>
	
	<xsl:template match="book">
		<tr>
			<td><xsl:value-of select="position()"/></td>
			<td><xsl:value-of select="name"/></td>
			<td><xsl:value-of select="authors"/></td>
		</tr>
	</xsl:template>
</xsl:stylesheet>
 

 

你可能感兴趣的:(spring,xml,.net,Hibernate,XSL)