1. 在解析的过程中,此版本用dom4j解析
test.xml中的encoding="GBK"
test.xsl中的encoding="GBK"
两个文件中的encoding是相同的
但经过jaxp的TransFormer转换后却输出成了UTF_8编码
java 代码
- Document document = DocumentHelper.parseText(xmldoc.trim());
- // load the transformer using JAXP
- TransformerFactory factory = TransformerFactory.newInstance();
- //XSLT样式表是静态存储在文件中的,
- //javax.XML.transform.Templates接口把它们解析好了进内存里缓存起来
- //Templates templates = factory.newTemplates();
- Transformer transformer = factory.newTransformer(new StreamSource(stylesheet));
- Properties props = transformer.getOutputProperties();
- props.setProperty(OutputKeys.ENCODING,"GBK");
- props.setProperty(OutputKeys.METHOD,"html");
- props.setProperty(OutputKeys.VERSION,"4.0");
- // props.list(System.out);
- transformer.setOutputProperties(props);
- //now lets style the given document
- // DOMProcessingInstruction processingInstruction = new DOMProcessingInstruction("xml-stylesheet", "type='text/xsl' href='hello.xsl'");
- // document.add(processingInstruction);
- // System.out.println(document.asXML());
- DocumentSource docSource = new DocumentSource(document);
- StringWriter strWriter = new StringWriter();
- //DocumentResult docResult = new DocumentResult();
- StreamResult docResult =new StreamResult(strWriter) ;
- transformer.transform(docSource, docResult);
- // return the transformed document
- // Document docTrans = docResult.getDocument();
- // String writer = docResult.toString();
- //strWriter = (StringWriter) docResult.getWriter();
- System.out.println();
- String target = null;
- StringBuffer xmlSource = new StringBuffer();
- System.out.println("strWriter"+strWriter.toString());
通过TransFormerFactory中的参数:
1. StreamSource(String styleSheetFilePath)获取源样式文件,接受一个String对象,此处加载的styleSheetFilePath为*.xslt文件,xml样式文件,为xml转换作准备
2. TransFormer转换xml+xsl为html对象的时候,需要两个参数
2.1.DocumentSource(Document doc)此处获取xml文档对象
2.2.StreamResult(StringWriter strWriter)此处的输出对象,可以为任意的writer对象,但用StringWriter可以更容易些,输出自己想的html文件