JAXP解析XML+XSL转换过程

1. 在解析的过程中,此版本用dom4j解析

         test.xml中的encoding="GBK"

         test.xsl中的encoding="GBK"

   两个文件中的encoding是相同的

   但经过jaxp的TransFormer转换后却输出成了UTF_8编码

java 代码
  1. Document document = DocumentHelper.parseText(xmldoc.trim());   
  2. //           load the transformer using JAXP   
  3.             TransformerFactory factory = TransformerFactory.newInstance();   
  4.                
  5.                 //XSLT样式表是静态存储在文件中的,   
  6.                 //javax.XML.transform.Templates接口把它们解析好了进内存里缓存起来   
  7.             //Templates templates = factory.newTemplates();   
  8.                 Transformer transformer = factory.newTransformer(new StreamSource(stylesheet));   
  9.                 Properties props = transformer.getOutputProperties();   
  10.                 props.setProperty(OutputKeys.ENCODING,"GBK");   
  11.                 props.setProperty(OutputKeys.METHOD,"html");   
  12.                 props.setProperty(OutputKeys.VERSION,"4.0");   
  13.                    
  14. //              props.list(System.out);   
  15.                 transformer.setOutputProperties(props);   
  16.              //now lets style the given document   
  17. //              DOMProcessingInstruction processingInstruction = new DOMProcessingInstruction("xml-stylesheet", "type='text/xsl' href='hello.xsl'");   
  18. //              document.add(processingInstruction);   
  19. //              System.out.println(document.asXML());   
  20.                 DocumentSource docSource = new DocumentSource(document);   
  21.                 StringWriter strWriter = new StringWriter();   
  22.                 //DocumentResult docResult = new DocumentResult();   
  23.                 StreamResult docResult =new StreamResult(strWriter) ;   
  24.                 transformer.transform(docSource, docResult);   
  25.                 // return the transformed document   
  26. //              Document docTrans = docResult.getDocument();   
  27. //              String writer = docResult.toString();   
  28.                 //strWriter = (StringWriter) docResult.getWriter();   
  29.                 System.out.println();   
  30.                 String target = null;   
  31.                 StringBuffer xmlSource = new StringBuffer();   
  32.                    
  33.                 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文件

    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值