| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
package net.sf.saxon.ma.json; |
| 9 |
|
| 10 |
import net.sf.saxon.event.DocumentValidator; |
| 11 |
import net.sf.saxon.event.PipelineConfiguration; |
| 12 |
import net.sf.saxon.event.Receiver; |
| 13 |
import net.sf.saxon.event.StartTagBuffer; |
| 14 |
import net.sf.saxon.expr.XPathContext; |
| 15 |
import net.sf.saxon.expr.parser.ExplicitLocation; |
| 16 |
import net.sf.saxon.functions.OptionsParameter; |
| 17 |
import net.sf.saxon.functions.SystemFunction; |
| 18 |
import net.sf.saxon.ma.map.MapItem; |
| 19 |
import net.sf.saxon.om.NodeInfo; |
| 20 |
import net.sf.saxon.om.Sequence; |
| 21 |
import net.sf.saxon.trans.XPathException; |
| 22 |
import net.sf.saxon.type.Type; |
| 23 |
import net.sf.saxon.value.BooleanValue; |
| 24 |
import net.sf.saxon.value.EmptySequence; |
| 25 |
import net.sf.saxon.value.SequenceType; |
| 26 |
import net.sf.saxon.value.StringValue; |
| 27 |
|
| 28 |
import java.util.Map; |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
public class XMLToJsonFn extends SystemFunction { |
| 34 |
|
| 35 |
public static OptionsParameter makeOptionsParameter() { |
| 36 |
OptionsParameter xmlToJsonOptions = new OptionsParameter(); |
| 37 |
xmlToJsonOptions.addAllowedOption("indent", SequenceType.SINGLE_BOOLEAN, BooleanValue.FALSE); |
| 38 |
return xmlToJsonOptions; |
| 39 |
} |
| 40 |
|
| 41 |
public Sequence<?> call(XPathContext context, Sequence[] arguments) throws XPathException { |
| 42 |
NodeInfo xml = (NodeInfo) arguments[0].head(); |
| 43 |
if (xml == null) { |
| 44 |
return EmptySequence.getInstance(); |
| 45 |
} |
| 46 |
|
| 47 |
boolean indent = false; |
| 48 |
if (getArity() > 1) { |
| 49 |
MapItem suppliedOptions = (MapItem) arguments[1].head(); |
| 50 |
Map<String, Sequence<?>> options = getDetails().optionDetails.processSuppliedOptions(suppliedOptions, context); |
| 51 |
indent = ((BooleanValue)options.get("indent").head()).getBooleanValue(); |
| 52 |
} |
| 53 |
|
| 54 |
PipelineConfiguration pipe = context.getController().makePipelineConfiguration(); |
| 55 |
pipe.setXPathContext(context); |
| 56 |
JsonReceiver receiver = new JsonReceiver(pipe); |
| 57 |
receiver.setIndenting(indent); |
| 58 |
Receiver r = receiver; |
| 59 |
if (xml.getNodeKind() == Type.DOCUMENT) { |
| 60 |
r = new DocumentValidator(r, "FOJS0006"); |
| 61 |
} |
| 62 |
StartTagBuffer stb = new StartTagBuffer(r); |
| 63 |
pipe.setComponent(StartTagBuffer.class.getName(), stb); |
| 64 |
stb.setPipelineConfiguration(pipe); |
| 65 |
stb.open(); |
| 66 |
xml.copy(stb, 0, ExplicitLocation.UNKNOWN_LOCATION); |
| 67 |
stb.close(); |
| 68 |
return new StringValue(receiver.getJsonString()); |
| 69 |
} |
| 70 |
|
| 71 |
public String getStreamerName() { |
| 72 |
return "XmlToJsonFn"; |
| 73 |
} |
| 74 |
|
| 75 |
} |