xsl本身就是一个构型良好的xml,它能够把一个xml文档转换成另外一个xml文档,或者转换成文本文件、html文件等等。这里就是利用xsl来动态的生成我们想要的java文件(从某种角度看,java代码其实也就是一个文本文件),希望能够通过这篇文章,看到xml以及相关的技术所具有的强大能力!
这里首先给一个xml例子,我们将通过一个xsl从该xml文件中抽取有用的信息来生成java代码(实际上是一个javabean):
[code]
offers to its customers
tested on animals
product to its customers
[/code]
下面我就直接给出转换的xsl,如果大家对xsl不是很了解的话,可以先看一些资料,了解之后就会明白了。我在里面稍微做了些注释:
[code]
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:java="http://xml.apache.org/xslt/java" exclude-result-prefixes="java"> /** * * This class has been generated by the XSLT processor from the metadata */ public class /** * Creates a new instance of the select="name"/> bean */ public } private /** * Sets * @param select="comments"/> */ public void set of select="type"/> of select="name"/>) { this. select="name"/>; } /** * Returns * @return */ public select="$cname"/>() { return }
[/code]
好了,完成以上工作之后,只要在cmd中,输入如下的命令行,就可以获得我们想要的结果了:
java org.apache.xalan.xslt.Process -in xmlSource -xsl stylesheet -out outputfile
这里列出结果:
[code]
/**
* This bean represents a product that the company offers to its
customers
* This class has been generated by the XSLT processor from the
metadata
*/
public class Product {
/**
* Creates a new instance of the Product bean
*/
public Product() {}
private int code;
/**
* Sets the product inventory code
* @param code is the product inventory code
*/
public void setCode(int code) {
this.code = code;
}
/**
* Returns the product inventory code
* @return the product inventory code
*/
public int getCode() {
return code;
}
private String name;
/**
* Sets the product name
* @param name is the product name
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns the product name
* @return the product name
*/
public String getName() {
return name;
}
private boolean testedOnAnimals;
/**
* Sets the flag that indicates if the product was tested on animals
* @param testedOnAnimals is the flag that indicates if the product
was tested on animals
*/
public void setTestedOnAnimals(boolean testedOnAnimals) {
this.testedOnAnimals = testedOnAnimals;
}
/**
* Returns the flag that indicates if the product was tested on
animals
* @return the flag that indicates if the product was tested on
animals
*/
public boolean isTestedOnAnimals() {
return testedOnAnimals;
}
private java.util.Date availableSince;
/**
* Sets the date when the company started offering this product to
its customers
* @param availableSince is the date when the company started
offering this product to its customers
*/
public void setAvailableSince(java.util.Date availableSince) {
this.availableSince = availableSince;
}
/**
* Returns the date when the company started offering this product
to its customers
* @return the date when the company started offering this product
to its customers
*/
public java.util.Date getAvailableSince() {
return availableSince;
}
}
[/code]
总结:
1. 在熟悉了xsl的基本使用之后,理解以上的内容并不是困难;
2. 这样做是比较适合预先知道了某些逻辑功能,但由于某种原因,需要动态生成,或者是为了节省不必要的重复工作,可以通过它自动生成代码;
3. 修改这个xsl比较方便。
sjoy

