DOM4J 使用简介(二)

6 用XSLT转换XML

    public Document styleDocument(

       Document document,

       String stylesheet

    ) throws Exception {

    // load the transformer using JAXP

    TransformerFactory factory = TransformerFactory.newInstance();

    Transformer transformer = factory.newTransformer(

       new StreamSource( stylesheet )

    );

    // now lets style the given document

    DocumentSource source = new DocumentSource( document );

    DocumentResult result = new DocumentResult();

    transformer.transform( source, result );

    // return the transformed document

    Document transformedDoc = result.getDocument();

    return transformedDoc;

} 

7. 创建XML
  一般创建XML是写文件前的工作,这就像StringBuffer一样容易。

     public Document createDocument() {

       Document document = DocumentHelper.createDocument();

       Element root = document.addElement(root);

       Element author1 =

           root

              .addElement(author)

              .addAttribute(name, James)

              .addAttribute(location, UK)

              .addText(James Strachan);

       Element author2 =

           root

              .addElement(author)

              .addAttribute(name, Bob)

              .addAttribute(location, US)

              .addText(Bob McWhirter);

       return document;

    } 

8. 文件输出
    一个简单的输出方法是将一个Document或任何的Node通过write方法输出

     FileWriter out = new FileWriter( foo.xml );

    document.write(out); 

  如果你想改变输出的格式,比如美化输出或缩减格式,可以用XMLWriter类

     public void write(Document document) throws IOException {

       // 指定文件

       XMLWriter writer = new XMLWriter(

           new FileWriter( output.xml )

       );

       writer.write( document );

       writer.close();

       // 美化格式

       OutputFormat format = OutputFormat.createPrettyPrint();

       writer = new XMLWriter( System.out, format );

       writer.write( document );

       // 缩减格式

       format = OutputFormat.createCompactFormat();

       writer = new XMLWriter( System.out, format );

       writer.write( document );

    } 

如何,DOM4J够简单吧,当然,还有一些复杂的应用没有提到,如ElementHandler等。如果你动心了,那就一起来用DOM4J.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值