/// <summary>
        /// Create an XdmValue from an underlying Saxon ValueRepresentation object.
        /// This method is provided for the benefit of applications that need to mix
        /// use of the Saxon .NET API with direct use of the underlying objects
        /// and methods offered by the Java implementation.
        /// </summary>
        /// <param name="value">An object representing an XDM value in the
        /// underlying Saxon implementation.</param>
        /// <returns>An XdmValue that wraps the underlying Saxon value
        /// representation.</returns>

        public static XdmValue Wrap(ValueRepresentation value) {
            XdmValue result;
            if (value == null || value is EmptySequence) {
                return XdmEmptySequence.INSTANCE;
            } else if (value is JAtomicValue) {
                result = new XdmAtomicValue();
            } else if (value is NodeInfo) {
                result = new XdmNode();
            } else {
                result = new XdmValue();
            }
            result.value = value;
            return result;
        }
Пример #2
0
        /// <summary>
        /// Load an XML document supplied as raw (lexical) XML on a Stream.
        /// </summary>
        /// <remarks>
        /// <para>The document is parsed using the <c>System.Xml</c> parser.</para>
        /// <para>Before calling this method, the BaseUri property must be set to identify the
        /// base URI of this document, used for resolving any relative URIs contained within it.</para>
        /// <para>Note that the Microsoft <c>System.Xml</c> parser does not report whether attributes are
        /// defined in the DTD as being of type <c>ID</c> and <c>IDREF</c>. This is true whether or not
        /// DTD-based validation is enabled. This means that such attributes are not accessible to the
        /// <c>id()</c> and <c>idref()</c> functions.</para>
        /// </remarks>
        /// <param name="input">The Stream containing the XML source to be parsed</param>
        /// <returns>An <c>XdmNode</c>, the document node at the root of the tree of the resulting
        /// in-memory document
        /// </returns>

        public XdmNode Build(Stream input)
        {
            if (baseUri == null)
            {
                throw new ArgumentException("No base URI suppplied");
            }
            Source source = new StreamSource(new DotNetInputStream(input));

            source.setSystemId(baseUri.ToString());
            source = augmentSource(source);
            StaticQueryContext env = new StaticQueryContext(config);
            //env.setURIResolver(new DotNetURIResolver(xmlResolver));
            DocumentInfo doc = env.buildDocument(source);

            return((XdmNode)XdmValue.Wrap(doc));
        }
Пример #3
0
        static void Main(string[] args)
        {
            string infile = @"c:\daisybooks\verysimplebook\verysimplebook.xml";
            string infile_dir = @"c:\daisybooks\verysimplebook\";
            string xsltfile = @"c:\devel\amis\trunk\amis\bin\xslt\dtbook\dtbook2xhtml.xsl";
            string outfile = @"c:\devel\amis\sandbox\dtbooktransformer_out.xml";

            // Create a Processor instance.
            Processor processor = new Processor();

            // Load the source document
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(infile));

            // Create a transformer for the stylesheet.
            XsltTransformer transformer =
                processor.NewXsltCompiler().Compile(new Uri(xsltfile)).Load();

            QName basedir = new QName("", "baseDir");

            List<XdmAtomicValue> elementNames = new List<XdmAtomicValue>();
            elementNames.Add(new XdmAtomicValue(infile_dir));
            XdmValue basedir_value = new XdmValue(elementNames);

            transformer.SetParameter(basedir, basedir_value);

            // Set the user-written XmlResolver
            UserXmlResolver runTimeResolver = new UserXmlResolver();
            runTimeResolver.Message = "** Calling transformation-time XmlResolver: ";
            transformer.InputXmlResolver = runTimeResolver;

            // Set the root node of the source document to be the initial context node
            transformer.InitialContextNode = input;

            /*
             *  String outfile = "OutputFromXsltSimple2.xml";
            Serializer serializer = new Serializer();
            serializer.SetOutputStream(new FileStream(outfile, FileMode.Create, FileAccess.Write));
            */
              // Create a serializer, with output to the standard output stream
            Serializer serializer = new Serializer();
            serializer.SetOutputWriter(Console.Out);

            // Transform the source XML and serialize the result document
            transformer.Run(serializer);

            Console.ReadLine();
        }
Пример #4
0
        public net.sf.saxon.s9api.XdmValue call(net.sf.saxon.s9api.XdmValue[] xvarr)
        {
            XdmValue[] values = new XdmValue[xvarr.Length];
            int        len    = xvarr.Length;

            for (int i = 0; i < len; i++)
            {
                values[i] = XdmValue.Wrap(xvarr[i].getUnderlyingValue());
            }
            try {
                XdmValue result = definition.Call(values);
                return(XdmValue.FromGroundedValueToJXdmValue(result.value));
            }
            catch (Exception ex) {
                throw new DynamicError(ex.Message);
            }
        }
Пример #5
0
        /// <summary>
        /// Copy an XdmValue to an XmlDestination
        /// </summary>
        /// <remarks>
        /// This method can be used to copy any kind of <c>XdmValue</c> to any kind
        /// of <c>XdmDestination</c>. The supplied <c>XdmValue</c> is first converted
        /// to an XML document according to the rules of the XSLT/XQuery serialization
        /// specification (for example, if the <c>XdmValue</c> is a sequence of atomic
        /// values, they will be turned in a text node in which the values are converted
        /// to strings and separated by single spaces). The resulting document is then
        /// written to the supplied <c>XmlDestination</c>.</remarks>
        /// <param name="sequence">The value to be written</param>
        /// <param name="destination">The destination to which the value should be written</param>
        ///

        public void WriteXdmValue(XdmValue sequence, XmlDestination destination)
        {
            JResult   result = destination.GetResult();
            JReceiver r      = config.getSerializerFactory().getReceiver(result,
                                                                         config.makePipelineConfiguration(), new JProperties());

            r = new JNamespaceReducer(r);
            JTreeReceiver tree = new JTreeReceiver(r);

            tree.open();
            tree.startDocument(0);
            foreach (XdmItem it in sequence)
            {
                tree.append((Item)it.Unwrap(), 0, JNodeInfo.__Fields.ALL_NAMESPACES);
            }
            tree.endDocument();
            tree.close();
        }
Пример #6
0
        /// <summary>
        /// Execute an updating query.
        /// </summary>
        /// <returns>An array containing the root nodes of documents that have been
        /// updated by the query.</returns>
        /// <exception cref="DynamicError">Throws a <c>DynamicError</c> if any run-time failure
        /// occurs while evaluating the expression, or if the expression is not an
        /// updating query.</exception>

        public XdmNode[] RunUpdate()
        {
            try
            {
                evaluator.run();
                java.util.Iterator updatedDocsIter = evaluator.getUpdatedDocuments();
                List <XdmNode>     resultList      = new List <XdmNode>();

                for (; updatedDocsIter.hasNext();)

                {
                    resultList.Add((XdmNode)XdmValue.Wrap(((net.sf.saxon.s9api.XdmNode)updatedDocsIter.next()).getUnderlyingNode()));
                }
                XdmNode[] result = resultList.ToArray();
                return(result);
            }
            catch (JSaxonApiException err)
            {
                throw new DynamicError(err);
            }
        }
Пример #7
0
        /// <summary>
        /// Load an XML document, delivered using an XmlReader.
        /// </summary>
        /// <remarks>
        /// <para>The XmlReader is responsible for parsing the document; this method builds a tree
        /// representation of the document (in an internal Saxon format) and returns its document node.
        /// The XmlReader is not required to perform validation but it must expand any entity references.
        /// Saxon uses the properties of the <c>XmlReader</c> as supplied.</para>
        /// <para>Use of a plain <c>XmlTextReader</c> is discouraged, because it does not expand entity
        /// references. This should only be used if you know in advance that the document will contain
        /// no entity references (or perhaps if your query or stylesheet is not interested in the content
        /// of text and attribute nodes). Instead, with .NET 1.1 use an <c>XmlValidatingReader</c> (with <c>ValidationType</c>
        /// set to <c>None</c>). The constructor for <c>XmlValidatingReader</c> is obsolete in .NET 2.0,
        /// but the same effect can be achieved by using the <c>Create</c> method of <c>XmlReader</c> with
        /// appropriate <c>XmlReaderSettings</c></para>
        /// <para>Conformance with the W3C specifications requires that the <c>Normalization</c> property
        /// of an <c>XmlTextReader</c> should be set to <c>true</c>. However, Saxon does not insist
        /// on this.</para>
        /// <para>If the <c>XmlReader</c> performs schema validation, Saxon will ignore any resulting type
        /// information. Type information can only be obtained by using Saxon's own schema validator, which
        /// will be run if the <c>SchemaValidationMode</c> property is set to <c>Strict</c> or <c>Lax</c></para>
        /// <para>Note that the Microsoft <c>System.Xml</c> parser does not report whether attributes are
        /// defined in the DTD as being of type <c>ID</c> and <c>IDREF</c>. This is true whether or not
        /// DTD-based validation is enabled. This means that such attributes are not accessible to the
        /// <c>id()</c> and <c>idref()</c> functions.</para>
        /// <para>Note that setting the <c>XmlResolver</c> property of the <c>DocumentBuilder</c>
        /// has no effect when this method is used; if an <c>XmlResolver</c> is required, it must
        /// be set on the <c>XmlReader</c> itself.</para>
        /// </remarks>
        /// <param name="reader">The XMLReader that supplies the parsed XML source</param>
        /// <returns>An <c>XdmNode</c>, the document node at the root of the tree of the resulting
        /// in-memory document
        /// </returns>

        public XdmNode Build(XmlReader reader)
        {
            PullProvider pp = new DotNetPullProvider(reader);

            pp.setPipelineConfiguration(config.makePipelineConfiguration());
            // pp = new PullTracer(pp);  /* diagnostics */
            Source source = new PullSource(pp);

            source.setSystemId(reader.BaseURI);
            source = augmentSource(source);
            DocumentInfo doc = null;

            try
            {
                doc = config.buildDocument(source);
            }
            catch (net.sf.saxon.trans.XPathException e)
            {
                throw new StaticError(e);
            }
            return((XdmNode)XdmValue.Wrap(doc));
        }
Пример #8
0
        /// <summary>
        /// Execute an updating query.
        /// </summary>
        /// <returns>An array containing the root nodes of documents that have been
        /// updated by the query.</returns>
        /// <exception cref="DynamicError">Throws a DynamicError if any run-time failure
        /// occurs while evaluating the expression, or if the expression is not an
        /// updating query.</exception>

        public XdmNode[] RunUpdate()
        {
            if (!exp.isUpdateQuery())
            {
                throw new DynamicError("Not an updating query");
            }
            try
            {
                java.util.Set updatedDocs = exp.runUpdate(context);
                XdmNode[]     result      = new XdmNode[updatedDocs.size()];
                int           i           = 0;
                for (java.util.Iterator iter = updatedDocs.iterator(); iter.hasNext();)
                {
                    result[i++] = (XdmNode)XdmValue.Wrap((NodeInfo)iter.next());
                }
                return(result);
            }
            catch (JXPathException err)
            {
                throw new DynamicError(err);
            }
        }
Пример #9
0
        /// <summary>
        /// Copy an XdmValue to an XmlDestination
        /// </summary>
        /// <remarks>
        /// This method can be used to copy any kind of <c>XdmValue</c> to any kind
        /// of <c>XdmDestination</c>. The supplied <c>XdmValue</c> is first converted
        /// to an XML document according to the rules of the XSLT/XQuery serialization
        /// specification (for example, if the <c>XdmValue</c> is a sequence of atomic
        /// values, they will be turned in a text node in which the values are converted
        /// to strings and separated by single spaces). The resulting document is then
        /// written to the supplied <c>XmlDestination</c>.</remarks>
        /// <param name="sequence">The value to be written</param>
        /// <param name="destination">The destination to which the value should be written</param>
        ///

        public void WriteXdmValue(XdmValue sequence, XmlDestination destination)
        {
            try
            {
                JPipelineConfiguration pipe = config.makePipelineConfiguration();
                JResult   result            = destination.GetResult(pipe);
                JReceiver r = config.getSerializerFactory().getReceiver(result,
                                                                        pipe, destination.GetOutputProperties());
                r = new JNamespaceReducer(r);
                JTreeReceiver tree = new JTreeReceiver(r);
                tree.open();
                tree.startDocument(0);
                foreach (XdmItem it in sequence)
                {
                    tree.append((Item)it.Unwrap(), 0, JNodeInfo.__Fields.ALL_NAMESPACES);
                }
                tree.endDocument();
                tree.close();
            } catch (JXPathException err) {
                throw new DynamicError(err);
            }
        }
Пример #10
0
        /// <summary>
        /// Create an XdmValue from an underlying Saxon ValueRepresentation object.
        /// This method is provided for the benefit of applications that need to mix
        /// use of the Saxon .NET API with direct use of the underlying objects
        /// and methods offered by the Java implementation.
        /// </summary>
        /// <param name="value">An object representing an XDM value in the
        /// underlying Saxon implementation.</param>
        /// <returns>An XdmValue that wraps the underlying Saxon value
        /// representation.</returns>

        public static XdmValue Wrap(ValueRepresentation value)
        {
            XdmValue result;

            if (value == null || value is EmptySequence)
            {
                return(XdmEmptySequence.INSTANCE);
            }
            else if (value is JAtomicValue)
            {
                result = new XdmAtomicValue();
            }
            else if (value is NodeInfo)
            {
                result = new XdmNode();
            }
            else
            {
                result = new XdmValue();
            }
            result.value = value;
            return(result);
        }
Пример #11
0
        ///<summary>
        /// Call a global user-defined function in the compiled query.
        ///</summary>
        ///<remarks>
        /// If this is called more than once (to evaluate the same function repeatedly with different arguments,
        /// or to evaluate different functions) then the sequence of evaluations uses the same values of global
        /// variables including external variables (query parameters); the effect of any changes made to query parameters
        /// between calls is undefined.
        /// </remarks>
        /// <param name="function">
        /// The name of the function to be called
        /// </param>
        /// <param name="arguments">
        /// The values of the arguments to be supplied to the function. These
        /// must be of the correct type as defined in the function signature (there is no automatic
        /// conversion to the required type).
        /// </param>
        /// <exception cref="ArgumentException">If no function has been defined with the given name and arity
        /// or if any of the arguments does not match its required type according to the function
        /// signature.</exception>
        /// <exception cref="DynamicError">If a dynamic error occurs in evaluating the function.
        /// </exception>

        public XdmValue CallFunction(QName function, XdmValue[] arguments)
        {
            JUserFunction fn = exp.getStaticContext().getUserDefinedFunction(
                function.Uri, function.LocalName, arguments.Length);

            if (fn == null)
            {
                throw new ArgumentException("No function with name " + function.ClarkName +
                                            " and arity " + arguments.Length + " has been declared in the query");
            }
            try {
                // TODO: use the same controller in other interfaces such as run(), and expose it in a trapdoor API
                if (controller == null)
                {
                    controller = exp.newController();
                    context.initializeController(controller);
                    controller.defineGlobalParameters();
                }
                ValueRepresentation[] vr = new ValueRepresentation[arguments.Length];

                for (int i = 0; i < arguments.Length; i++)
                {
                    SequenceType type = fn.getParameterDefinitions()[i].getRequiredType();
                    vr[i] = arguments[i].Unwrap();
                    if (!type.matches(Value.asValue(vr[i]), controller.getConfiguration()))
                    {
                        throw new ArgumentException("Argument " + (i + 1) +
                                                    " of function " + function.ClarkName +
                                                    " does not match the required type " + type.toString());
                    }
                }
                ValueRepresentation result = fn.call(vr, controller);
                return(XdmValue.Wrap(result));
            } catch (JXPathException e) {
                throw new DynamicError(e);
            }
        }
Пример #12
0
 /// <summary>
 /// Determine whether this item type matches a given item.
 /// </summary>
 /// <param name="item">the item to be tested against this item type</param>
 /// <returns>true if the item matches this item type, false if it does not match.</returns>
 virtual public bool Matches(XdmItem item)
 {
     return(type.matches((net.sf.saxon.s9api.XdmItem)XdmValue.FromGroundedValueToJXdmValue(item.value)));
 }
Пример #13
0
        /// <summary>
        /// Set the value of an external variable declared in the query.
        /// </summary>
        /// <param name="name">The name of the external variable, expressed
        /// as a QName. If an external variable of this name has been declared in the
        /// query prolog, the given value will be assigned to the variable. If the
        /// variable has not been declared, calling this method has no effect (it is
        /// not an error).</param>
        /// <param name="value">The value to be given to the external variable.
        /// If the variable declaration defines a required type for the variable, then
        /// this value must match the required type: no conversions are applied.</param>

        public void SetExternalVariable(QName name, XdmValue value)
        {
            context.setParameter(name.ClarkName, value.Unwrap());
        }
Пример #14
0
        /// <summary>
        /// Set the value of an external variable declared in the query.
        /// </summary>
        /// <param name="name">The name of the external variable, expressed
        /// as a QName. If an external variable of this name has been declared in the
        /// query prolog, the given value will be assigned to the variable. If the
        /// variable has not been declared, calling this method has no effect (it is
        /// not an error).</param>
        /// <param name="value">The value to be given to the external variable.
        /// If the variable declaration defines a required type for the variable, then
        /// this value must match the required type: no conversions are applied.</param>

        public void SetExternalVariable(QName name, XdmValue value)
        {
            context.setParameter(name.ToStructuredQName(), value.Unwrap());
        }
Пример #15
0
 public override object wrapAsXdmValue(JValue value)
 {
     return(XdmValue.Wrap(value));
 }
Пример #16
0
 /// <summary>
 /// Create a new XdmValue by concatenating the sequences of items in this XdmValue and another XdmValue
 /// </summary>
 /// <remarks>
 /// Neither of the input XdmValue objects is modified by this operation
 /// </remarks>
 /// <param name="otherValue">
 /// The other XdmValue, whose items are to be appended to the items from this XdmValue
 /// </param>
 
 public XdmValue Append(XdmValue otherValue) {
     JArrayList list = new JArrayList();
     foreach (XdmItem item in this) {
         list.add(item.Unwrap());
     }
     foreach (XdmItem item in otherValue) {
         list.add(item.Unwrap());
     }
     return XdmValue.Wrap(new SequenceExtent(list));
 }
Пример #17
0
        /// <summary>
        /// Set the value of a stylesheet parameter.
        /// </summary>
        /// <param name="name">The name of the parameter, expressed
        /// as a QName. If a parameter of this name has been declared in the
        /// stylesheet, the given value will be assigned to the variable. If the
        /// variable has not been declared, calling this method has no effect (it is
        /// not an error).</param>
        /// <param name="value">The value to be given to the parameter.
        /// If the parameter declaration defines a required type for the variable, then
        /// this value will be converted in the same way as arguments to function calls
        /// (for example, numeric promotion is applied).</param>

        public void SetParameter(QName name, XdmValue value)
        {
            controller.setParameter(name.ClarkName, value.Unwrap());
        }
Пример #18
0
 /// <summary>
 /// Serialize an <c>XdmNode</c> to the selected output destination using this serializer.
 /// </summary>
 /// <param name="node">The node to be serialized</param>
 /// <remarks>since 9.8</remarks>
 public void SerializeXdmNode(XdmNode node)
 {
     serializer.serializeNode((net.sf.saxon.s9api.XdmNode)XdmValue.FromGroundedValueToJXdmValue(node.value));
 }
Пример #19
0
        /// <summary>
        /// Set the value of a variable
        /// </summary>
        /// <param name="name">The name of the variable. This must match the name of a variable
        /// that was declared to the XPathCompiler. No error occurs if the expression does not
        /// actually reference a variable with this name.</param>
        /// <param name="value">The value to be given to the variable.</param>
        

        public void SetVariable(QName name, XdmValue value)
        {
            JXPathVariable var = null;
            String uri = (name.Uri == null ? "" : name.Uri);
            String local = name.LocalName;
            foreach (JXPathVariable v in declaredVariables)
            {
                String vuri = v.getVariableQName().getURI();
                if (vuri == null)
                {
                    vuri = "";
                }
                if (vuri == uri && v.getVariableQName().getLocalPart() == local)
                {
                    var = v;
                    break;
                }
            }
            if (var == null)
            {
                // TODO: this seems to conflict with the documentation of the method
                throw new ArgumentException("Variable has not been declared: " + name);
            }
            dynamicContext.setVariable(var, value.Unwrap());
        }
Пример #20
0
 /// <summary>
 /// Invoke the function
 /// </summary>
 /// <param name="arguments">The arguments to the function</param>
 /// <param name="processor">The Saxon processor, used to provide context information</param>
 /// <returns>The result of calling the function</returns>
 /// 
 public XdmValue invoke(XdmValue[] arguments, Processor processor)
 {
     SequenceIterator[] args = new SequenceIterator[arguments.Length];
     for (int i = 0; i < arguments.Length; i++)
     {
         args[i] = Value.asIterator(arguments[i].Unwrap());
     }
     JXPathContext context = processor.config.getConversionContext();
     SequenceIterator result = ((JFunctionItem)value).invoke(args, context);
     return XdmValue.Wrap(JSequenceExtent.makeSequenceExtent(result));
 }
Пример #21
0
        /// <summary>
        /// Create an atomic value that wraps an external object. Such values can be used
        /// in conjunction with extension functions.
        /// </summary>
        /// <param name="external">The object to be wrapped.</param>
        /// <returns>The wrapped object</returns>

        public static XdmAtomicValue wrapExternalObject(object external)
        {
            return((XdmAtomicValue)XdmValue.Wrap(new DotNetObjectValue(external)));
        }
Пример #22
0
 public Outcome(XdmValue value)
 {
     this.value = value;
 }
        /// <summary>
        /// Set the value of a variable
        /// </summary>

        public void SetVariable(QName name, XdmValue value) {
            int slot = env.getSlotNumber(name.ToQNameValue());
            if (slot == -1) {
                throw new ArgumentException("Variable has not been declared: " + name);
            }
            variableValues[slot] = value.Unwrap();
        }
Пример #24
0
        /// <summary>
        /// Set the value of a stylesheet parameter.
        /// </summary>
        /// <param name="name">The name of the parameter, expressed
        /// as a QName. If a parameter of this name has been declared in the
        /// stylesheet, the given value will be assigned to the variable. If the
        /// variable has not been declared, calling this method has no effect (it is
        /// not an error).</param>
        /// <param name="value">The value to be given to the parameter.
        /// If the parameter declaration defines a required type for the variable, then
        /// this value will be converted in the same way as arguments to function calls
        /// (for example, numeric promotion is applied).</param>

        public void SetParameter(QName name, XdmValue value)
        {
            controller.setParameter(name.ClarkName, value.Unwrap());
        }
Пример #25
0
 /// <summary>
 /// Get the value that has set for a schema processor (a parameter defined in the schema using the <c>saxon:param</c>
 /// extension)
 /// </summary>
 /// <param name="name">the parameter whose name is required</param>
 /// <returns>the value that has been set for the parameter, or the EmptySequence if no value has been set</returns>
 public XdmValue GetParameter(QName name)
 {
     net.sf.saxon.s9api.XdmValue value = schemaValidator.getParameter(name.UnderlyingQName());
     return(value == null ? null : XdmValue.Wrap(value.getUnderlyingValue()));
 }
Пример #26
0
 /// <summary>
 /// Set the value of a schema parameter (a parameter defined in the schema using the <c>saxon:param</c> extension)
 /// </summary>
 /// <param name="name">the name of the schema parameter, as a QName</param>
 /// <param name="value">the value of the schema  parameter, or null to clear a previously set value</param>
 public void SetParameter(QName name, XdmValue value)
 {
     try {
         schemaValidator.setParameter(name.UnderlyingQName(), value == null ? null : XdmValue.FromGroundedValueToJXdmValue(value.value));
     } catch (net.sf.saxon.s9api.SaxonApiUncheckedException ex) {
         throw new StaticError(ex);
     }
 }
Пример #27
0
        /// <summary>
        /// Set the value of an external variable declared in the query.
        /// </summary>
        /// <param name="name">The name of the external variable, expressed
        /// as a <c>QName</c>. If an external variable of this name has been declared in the
        /// query prolog, the given value will be assigned to the variable. If the
        /// variable has not been declared, calling this method has no effect (it is
        /// not an error).</param>
        /// <param name="value">The value to be given to the external variable.
        /// If the variable declaration defines a required type for the variable, then
        /// this value must match the required type: no conversions are applied.</param>

        public void SetExternalVariable(QName name, XdmValue value)
        {
            evaluator.setExternalVariable(new JXQName(name.ToStructuredQName()), value == null ? null : XdmValue.FromGroundedValueToJXdmValue(value.value));
        }
Пример #28
0
        /// <summary>
        /// Set the value of an external variable declared in the query.
        /// </summary>
        /// <param name="name">The name of the external variable, expressed
        /// as a QName. If an external variable of this name has been declared in the
        /// query prolog, the given value will be assigned to the variable. If the
        /// variable has not been declared, calling this method has no effect (it is
        /// not an error).</param>
        /// <param name="value">The value to be given to the external variable.
        /// If the variable declaration defines a required type for the variable, then
        /// this value must match the required type: no conversions are applied.</param>

        public void SetExternalVariable(QName name, XdmValue value)
        {
            context.setParameter(name.ClarkName, value.Unwrap());
        }
Пример #29
0
    ///<summary>
    /// Call a global user-defined function in the compiled query.
    ///</summary>
    ///<remarks>
    /// If this is called more than once (to evaluate the same function repeatedly with different arguments,
    /// or to evaluate different functions) then the sequence of evaluations uses the same values of global
    /// variables including external variables (query parameters); the effect of any changes made to query parameters
    /// between calls is undefined.
    /// </remarks>
    /// <param name="function">
    /// The name of the function to be called
    /// </param>
    /// <param name="arguments">
    /// The values of the arguments to be supplied to the function. These
    /// must be of the correct type as defined in the function signature (there is no automatic
    /// conversion to the required type).
    /// </param>
    /// <exception cref="ArgumentException">If no function has been defined with the given name and arity
    /// or if any of the arguments does not match its required type according to the function
    /// signature.</exception>
    /// <exception cref="DynamicError">If a dynamic error occurs in evaluating the function.
    /// </exception>

    public XdmValue CallFunction(QName function, XdmValue[] arguments) {
        JUserFunction fn = exp.getStaticContext().getUserDefinedFunction(
                function.Uri, function.LocalName, arguments.Length);
        if (fn == null) {
            throw new ArgumentException("No function with name " + function.ClarkName +
                    " and arity " + arguments.Length + " has been declared in the query");
        }
        try {
            // TODO: use the same controller in other interfaces such as run(), and expose it in a trapdoor API
            if (controller == null) {
                controller = exp.newController();
                context.initializeController(controller);
                controller.defineGlobalParameters();
            }
            ValueRepresentation[] vr = new ValueRepresentation[arguments.Length];

            for (int i=0; i<arguments.Length; i++) {
                SequenceType type = fn.getParameterDefinitions()[i].getRequiredType();
                vr[i] = arguments[i].Unwrap();
                if (!type.matches(Value.asValue(vr[i]), controller.getConfiguration())) {
                    throw new ArgumentException("Argument " + (i+1) +
                            " of function " + function.ClarkName +
                            " does not match the required type " + type.toString());
                }
            }
            ValueRepresentation result = fn.call(vr, controller);
            return XdmValue.Wrap(result);
        } catch (JXPathException e) {
            throw new DynamicError(e);
        }
    }
Пример #30
0
        /// <summary>Locate and compile a stylesheet identified by an &lt;?xml-stylesheet?&gt;
        /// processing instruction within a source document.
        /// </summary>
        /// <param name="source">The document node of the source document containing the
        /// xml-stylesheet processing instruction.</param>
        /// <returns>An <c>XsltExecutable</c> which represents the compiled stylesheet object.</returns>
        /// <remarks>There are some limitations in the current implementation. The media type
        /// is ignored, as are the other parameters of the xml-stylesheet instruction. The
        /// href attribute must either reference an embedded stylesheet within the same
        /// document or a non-embedded external stylesheet.</remarks>

        public XsltExecutable CompileAssociatedStylesheet(XdmNode source)
        {
            // TODO: lift the restrictions
            if (source == null || source.NodeKind != XmlNodeType.Document)
            {
                throw new ArgumentException("Source must be a document node");
            }
            IEnumerator kids     = source.EnumerateAxis(XdmAxis.Child);
            QName       xmlstyle = new QName("", "xml-stylesheet");

            while (kids.MoveNext())
            {
                XdmNode n = (XdmNode)kids.Current;
                if (n.NodeKind == XmlNodeType.ProcessingInstruction &&
                    n.NodeName.Equals(xmlstyle))
                {
                    // TODO: check the media type
                    String href = JProcInstParser.getPseudoAttribute(n.StringValue, "href");
                    if (href == null)
                    {
                        throw new DynamicError("xml-stylesheet processing instruction has no href attribute");
                    }
                    String fragment = null;
                    int    hash     = href.LastIndexOf('#');
                    if (hash == 0)
                    {
                        if (href.Length == 1)
                        {
                            throw new DynamicError("Relative URI of '#' is invalid");
                        }
                        fragment = href.Substring(1);
                        JNodeInfo target        = ((JDocumentInfo)source.value).selectID(fragment);
                        XdmNode   targetWrapper = null;
                        if (target == null)
                        {
                            // There's a problem here because the Microsoft XML parser doesn't
                            // report id values, so selectID() will never work. We work around that
                            // by looking for an attribute named "id" appearing on an xsl:stylesheet
                            // or xsl:transform element
                            QName       qid = new QName("", "id");
                            IEnumerator en  = source.EnumerateAxis(XdmAxis.Descendant);
                            while (en.MoveNext())
                            {
                                XdmNode x = (XdmNode)en.Current;
                                if (x.NodeKind == XmlNodeType.Element &&
                                    x.NodeName.Uri == "http://www.w3.org/1999/XSL/Transform" &&
                                    (x.NodeName.LocalName == "stylesheet" || x.NodeName.LocalName == "transform" &&
                                     x.GetAttributeValue(qid) == fragment))
                                {
                                    targetWrapper = x;
                                }
                            }
                        }
                        else
                        {
                            targetWrapper = (XdmNode)XdmValue.Wrap(target);
                        }
                        if (targetWrapper == null)
                        {
                            throw new DynamicError("No element with id='" + fragment + "' found");
                        }
                        return(Compile(targetWrapper));
                    }
                    else if (hash > 0)
                    {
                        throw new NotImplementedException("href cannot identify an embedded stylesheet in a different document");
                    }
                    else
                    {
                        Uri uri = new Uri(n.BaseUri, href);
                        return(Compile(uri));
                    }
                }
            }
            throw new DynamicError("xml-stylesheet processing instruction not found");
        }
Пример #31
0
        /// <summary>
        /// Create an XdmValue from an underlying Saxon ValueRepresentation object.
        /// This method is provided for the benefit of applications that need to mix
        /// use of the Saxon .NET API with direct use of the underlying objects
        /// and methods offered by the Java implementation.
        /// </summary>
        /// <param name="value">An object representing an XDM value in the
        /// underlying Saxon implementation. If the parameter is null,
        /// the method returns null.</param>
        /// <returns>An XdmValue that wraps the underlying Saxon value
        /// representation.</returns>

        public static XdmValue Wrap(ValueRepresentation value)
        {
            XdmValue result;
            if (value == null)
            {
                return null;
            }
            if (value is JEmptySequence)
            {
                return XdmEmptySequence.INSTANCE;
            }
            else if (value is JAtomicValue)
            {
                result = new XdmAtomicValue();
            }
            else if (value is NodeInfo)
            {
                result = new XdmNode();
            }
            else if (value is JSingletonItem)
            {
                value = ((JSingletonItem)value).asItem();
                result = new XdmNode();
            }
            else
            {
                result = new XdmValue();
            }
            result.value = value;
            return result;
        }