print xsl:message as TextArea中的String

时间:2014-12-16 16:09:13

标签: java xslt

我正在尝试在JTextArea中打印xsl:消息。我知道我必须使用MessageEmitter 这是我的Java代码:

public static void xslTransform(File xmlFile,File xslFile, JTextArea output){
StreamSource source = new StreamSource(xmlFile);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory transFact = new TransformerFactory.newInstance();
transFact.setAttribute(FeatureKeys.MESSAGE_EMITTER_CLASS, "net.sf.saxon.serialize.MessageEmitter");
Transformer transformer = transFact.newTransformer(new StreamSource(xslFile));
transformer.transform(source, result);

有人可以帮助我从<xsl:message>获取字符串吗?

这是我目前的代码:

public static void xslTransform(File xmlFile)throws IOException, TransformerException{
File xslFile = ...;
StreamSource xmlSource = new StreamSource(xmlFile);
StreamSource xslSource = new StreamSource(xslFile);
StreamResult result = new StreamResult (new StringWriter()); //maybe here is the problem?
TransformerFactory transformerFact = TransformerFactory.newInstance();
transformerFact.setAttribute(FeatureKeys.MESSAGE_EMITTER_CLASS, "MyMessageEmitter");
Transformer transformer = transformerFact.newTransformer(xslSource);
transformer.transform(xmlSource,result);
}

MyMessageEmitter类:

public class MyMessageEmitter extends net.sf.saxon.serialize.MessageEmitter{
String message;
private StringWriter stwriter = new StringWriter();
public void MyMessageEmitter() throws XPathException{
setWriter(stwriter);
}
@Override
public void close() throws XPathException{
super.close();
message=stwriter.toString();
System.out.println(message);
stwriter = new StringWriter();
}
}

为什么消息现在始终为null?

荷风

1 个答案:

答案 0 :(得分:0)

您指定为消息发射器的类是标准的Saxon消息发射器,但您要做的是实现自己的类。像这样:

public static class MyMessageEmitter extends net.sf.saxon.serialize.MessageEmitter {

   StringWriter writer = new StringWriter();

   public MyMessageEmitter() {
     setWriter(writer);
   }

   public void close() {
     super.close();
     String message = writer.toString();
     // now do what you want with the message
     writer = new StringWriter(); // ready for the next message
   }
}

然后......

transFact.setAttribute(FeatureKeys.MESSAGE_EMITTER_CLASS, "MyMessageEmitter");

使用Saxon的s9api接口而不是JAXP实际上会更容易一些,如果你是一个更有经验的Java程序员,我会指出你朝这个方向,但是当你对游戏不熟悉的时候它可能更容易采取小步骤。