xslt笔记(by quqi99)

xslt笔记(by quqi99)



作者:张华 发表于:2006-11-01 ( http://blog.csdn.net/quqi99 )

版权声明:可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本版权声明。

典型使用方法如下:

<!-- 名为copy_config的函数,参数为confignodes 。 注意:函数一定要写在调用它地方的前面 -->

<xsl:template name="config_config match="/">

<xsl:param name="confignodes" />

<http-service>

<!--拷贝一个元素及它的子元素-->

<xsl:copy-of select="$confignodes/web-container/access-log"/>

<!-- 拷贝本元素及其属性,不包括子元素 -->

    <xsl:value-of select="'&lt;availability-service '" disable-output-escapting="yes" />

<xsl:for-each select="$confignodes/availability-service/@*">

<xsl:value-of select="name()" />="<xsl:value-of select="." />"

</xsl:for-each>

<xsl:value-of select="'/&gt;'" disable-output-escapting="yes" />

</http-service>

</xsl:template>

<xsl:template match("/">

<xsl:for-each select="//config">

<config>

<!-- 调用名为copy_config的函数,传进的参数为confignodes-->

<xsl:call-template name="copy_config">

<xsl:with-param name="confignodes" select="." />

</xsl:call-template>

</config>

</xsl:for-each>

</xsl:template>

使用XSL API对XML进行转换:

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* @version 0.10 2009-11-2
* @author Zhang Hua
*/
public class Convertor {

public static void main(String[] args) throws Exception {
final boolean validateEnabled = true;
ClassLoader cl = Convertor.class.getClassLoader();
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource("test.xsl"));
transformer.setOutputProperty("indent", "yes");
transformer.setOutputProperty("encoding", "UTF-8");
InputStream is = cl.getResourceAsStream("domain.xml");

Source source = null;
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fac.newDocumentBuilder();
builder.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
if (validateEnabled)
// 不验证
return new InputSource(new StringReader("<?xml version=/"1.0/" encoding=/"UTF-8/"?>"));
else
// 根据DTD本地验证
return new InputSource("./test.dtd");
}
});
Document doc = builder.parse(is);
source = new DOMSource(doc);
// source = new StreamSource(is);

StringWriter result = new StringWriter();
transformer.transform(source, new StreamResult(result));
// transformer.transform(source, new StreamResult(new File("dest.xml")));
System.out.println(result.toString());
}
}

你可能感兴趣的:(XSL)