1 package net.sf.saxon.functions; 2 import net.sf.saxon.event.SequenceReceiver; 3 import net.sf.saxon.expr.StaticContext; 4 import net.sf.saxon.expr.XPathContext; 5 import net.sf.saxon.om.Item; 6 import net.sf.saxon.om.NodeInfo; 7 import net.sf.saxon.om.Validation; 8 import net.sf.saxon.style.ExpressionContext; 9 import net.sf.saxon.trace.Location; 10 import net.sf.saxon.trans.DynamicError; 11 import net.sf.saxon.trans.StaticError; 12 import net.sf.saxon.trans.XPathException; 13 import net.sf.saxon.value.StringValue; 14 15 import javax.xml.transform.OutputKeys ; 16 import javax.xml.transform.stream.StreamResult ; 17 import java.io.StringWriter ; 18 import java.util.Properties ; 19 20 21 26 27 public class Serialize extends SystemFunction implements XSLTFunction { 28 29 Properties outputProperties; 30 private transient boolean checked = false; 31 33 37 38 public void checkArguments(StaticContext env) throws XPathException { 39 if (checked) return; 40 checked = true; 41 super.checkArguments(env); 42 if (env instanceof ExpressionContext) { 43 45 49 if (!(argument[1] instanceof StringValue)) { 50 throw new StaticError("Second argument of saxon:serialize must be known at compile time"); 51 } 52 String format = ((StringValue)argument[1]).getStringValue(); 53 int fingerprint = -1; 54 if (!format.equals("")) { 55 fingerprint = ((ExpressionContext)env).getFingerprint(format, false); 56 if (fingerprint==-1) { 57 throw new StaticError("Output format '" + format + "' has not been defined"); 58 } 59 } 60 outputProperties = ((ExpressionContext)env).getXSLStylesheet().gatherOutputProperties(fingerprint); 61 } else { 62 outputProperties = new Properties (); 64 if (!(argument[1] instanceof StringValue)) { 65 throw new StaticError("Second argument of saxon:serialize must be known at compile time"); 66 } 67 outputProperties.setProperty(OutputKeys.METHOD, ((StringValue)argument[1]).getStringValue()); 68 } 69 } 70 71 74 75 public Item evaluateItem(XPathContext c) throws XPathException { 76 NodeInfo node = (NodeInfo)argument[0].evaluateItem(c); 77 if (node==null) { 78 return StringValue.EMPTY_STRING; 79 } 80 81 try { 82 StringWriter result = new StringWriter (); 83 XPathContext c2 = c.newMinorContext(); 84 c.setOriginatingConstructType(Location.SAXON_SERIALIZE); 85 86 c2.changeOutputDestination(outputProperties, 87 new StreamResult (result), 88 false, 89 Validation.PRESERVE, 90 null); 91 SequenceReceiver out = c2.getReceiver(); 92 out.open(); 93 node.copy(out, NodeInfo.ALL_NAMESPACES, true, locationId); 94 out.close(); 95 return new StringValue(result.toString()); 96 } catch (XPathException err) { 97 throw new DynamicError(err); 98 } 99 } 100 } 101 102 103 104 105 | Popular Tags |