Example #1
0
        public void Reading()
        {
            Stream        stm = Globals.GetResource(Globals.PubsNsResource);
            XmlTextReader tr  = new XmlTextReader(stm);

            XPathDocument  doc = new XPathDocument(tr);
            XPathNavigator nav = doc.CreateNavigator();

            // Dumps the entire document to output.
            XmlTextWriter tw = new XmlTextWriter(Console.Out);

            tw.WriteNode(new XPathNavigatorReader(nav), true);

            // Perform a query, then dump the first node (OuterXml) from the result.
            nav = doc.CreateNavigator();
            XmlNamespaceManager mgr = new XmlNamespaceManager(nav.NameTable);

            mgr.AddNamespace("mvp", "mvp-xml");
            XPathNodeIterator it = XPathCache.Select("//mvp:titles[mvp:title_id='BU2075']", nav, mgr);

            if (it.MoveNext())
            {
                XmlReader title = new XPathNavigatorReader(it.Current);
                // As it's a regular reader, we must first move it to content as usual.
                title.MoveToContent();
                Console.WriteLine(title.ReadOuterXml());
            }

            // Perform arbitrary movements, then serialize inner content.
            nav = doc.CreateNavigator();
            nav.MoveToFirstChild();
            nav.MoveToFirstChild();
            Console.WriteLine(new XPathNavigatorReader(nav).ReadInnerXml());
        }
        /// <summary>
        /// This code is just to show how it's used.
        /// If run it will throw exceptions.
        /// </summary>
        public void Test()
        {
            XPathNavigator    document = new XPathDocument(String.Empty).CreateNavigator();
            XPathNodeIterator it       = XPathCache.Select("/customer/order/item", document);

            it = XPathCache.Select("/customer/order[id=$id]/item", document,
                                   new XPathVariable("id", "23"));

            string[] ids = null;
            foreach (string id in ids)
            {
                it = XPathCache.Select("/customer/order[id=$id]/item", document,
                                       new XPathVariable("id", id));
            }

            XmlNamespaceManager mgr = new XmlNamespaceManager(document.NameTable);

            mgr.AddNamespace("po", "example-po");

            it = XPathCache.Select("/po:customer[id=$id]", document, mgr,
                                   new XPathVariable("id", "0736"));

            XmlDocument doc  = new XmlDocument();
            XmlNodeList list = XPathCache.SelectNodes("/customer", doc);
        }
Example #3
0
        public void DynamicVariable()
        {
            string expr  = "//mvp:titles[mvp:price > 10]";
            string dyn   = "//mvp:titles[mvp:price > $price]";
            int    price = 10;

            XPathNavigator      docnav = Document.CreateNavigator();
            XPathExpression     xpath  = docnav.Compile(expr);
            XmlNamespaceManager mgr    = new XmlNamespaceManager(docnav.NameTable);

            mgr.AddNamespace(Globals.MvpPrefix, Globals.MvpNamespace);
            xpath.SetContext(mgr);

            int count1 = Document.CreateNavigator().Select(xpath).Count;
            // Test with compiled expression.
            int count2 = XPathCache.Select(expr, Document.CreateNavigator(), mgr).Count;

            Assert.AreEqual(count1, count2);

            // Test with dynamic expression.
            count2 = XPathCache.Select(dyn, Document.CreateNavigator(),
                                       mgr, new XPathVariable("price", price)).Count;

            Assert.AreEqual(count1, count2);
        }
Example #4
0
        /// <summary>
        /// Evaluate an xpath expression against a list of xpath variables.
        /// </summary>
        /// <param name="xpath">XPath expression to evaluate</param>
        /// <param name="xpathVars">XPathVariable array to evaluate against</param>
        /// <returns>Object containing results of evaluation</returns>
        static public object Evaluate(string xpath, XPathVariable[] xpathVars)
        {
            XmlDocument emptyDoc = new XmlDocument();

            emptyDoc.LoadXml("<root/>");

            return(XPathCache.Evaluate(xpath, emptyDoc.CreateNavigator(), xpathVars));
        }
        /// <summary>
        /// Evaluates <see cref="XPointer"/> pointer and returns 
        /// iterator over pointed nodes.
        /// </summary>
        /// <remarks>Note, that returned XPathNodeIterator is already moved once.</remarks>
        /// <param name="nav">XPathNavigator to evaluate the 
        /// <see cref="XPointer"/> on.</param>
        /// <returns><see cref="XPathNodeIterator"/> over pointed nodes</returns>	    					
        public override XPathNodeIterator Evaluate(XPathNavigator nav)
        {
            XPathNodeIterator result = XPathCache.Select("id('" + ncName + "')", nav, (XmlNamespaceManager)null);
            if (result != null && result.MoveNext())
            {
                return result;
            }

            throw new NoSubresourcesIdentifiedException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.NoSubresourcesIdentifiedException, ncName));
        }
Example #6
0
 public override XPathNodeIterator Evaluate(XPathNavigator doc, XmlNamespaceManager nm)
 {
     try
     {
         return(XPathCache.Select(_xpath, doc, nm));
     }
     catch
     {
         return(null);
     }
 }
Example #7
0
 public static IEnumerable <XmlElement> ElementsByXPath(this XmlNode node, string xPath)
 {
     try
     {
         return(XPathCache.SelectNodes(xPath, node).OfType <XmlElement>());
     }
     catch (NullReferenceException)
     {
         return(node.SelectNodes(xPath).OfType <XmlElement>());
     }
 }
Example #8
0
        /// <summary>
        /// Evaluates <see cref="XPointer"/> pointer and returns
        /// iterator over pointed nodes.
        /// </summary>
        /// <remarks>Note, that returned XPathNodeIterator is already moved once.</remarks>
        /// <param name="nav">XPathNavigator to evaluate the
        /// <see cref="XPointer"/> on.</param>
        /// <returns><see cref="XPathNodeIterator"/> over pointed nodes</returns>
        public override XPathNodeIterator Evaluate(XPathNavigator nav)
        {
            XPathNodeIterator result = XPathCache.Select("id('" + _NCName + "')", nav, (XmlNamespaceManager)null);

            if (result != null && result.MoveNext())
            {
                return(result);
            }
            else
            {
                throw new NoSubresourcesIdentifiedException(SR.GetString("NoSubresourcesIdentifiedException", _NCName));
            }
        }
Example #9
0
        public void PrefixMapping()
        {
            string expr = "//mvp:titles[mvp:price > 10]";

            XPathNavigator docnav = Document.CreateNavigator();
            XPathExpression xpath = docnav.Compile(expr);
            XmlNamespaceManager mgr = new XmlNamespaceManager(docnav.NameTable);
            mgr.AddNamespace(Globals.MvpPrefix, Globals.MvpNamespace);
            xpath.SetContext(mgr);

            int count1 = Document.CreateNavigator().Select(xpath).Count;
            int count2 = XPathCache.Select(expr, Document.CreateNavigator(),
                new XmlPrefix(Globals.MvpPrefix, Globals.MvpNamespace, Document.CreateNavigator().NameTable)).Count;

            Assert.AreEqual(count1, count2);
        }
Example #10
0
        public void Sorted1()
        {
            string expr = "//mvp:titles";

            XPathNavigator      docnav = Document.CreateNavigator();
            XPathExpression     xpath  = docnav.Compile(expr);
            XmlNamespaceManager mgr    = new XmlNamespaceManager(docnav.NameTable);

            mgr.AddNamespace(Globals.MvpPrefix, Globals.MvpNamespace);
            xpath.SetContext(mgr);
            XPathExpression sort = docnav.Compile("mvp:price");

            sort.SetContext(mgr);
            xpath.AddSort(sort, XmlSortOrder.Ascending, XmlCaseOrder.LowerFirst, String.Empty, XmlDataType.Number);

            XPathNodeIterator it = Document.CreateNavigator().Select(xpath);

            DebugUtils.XPathNodeIteratorToConsole(it);

            it = Document.CreateNavigator().Select(xpath);

            it.MoveNext();
            it.Current.MoveToFirstChild();
            string id1 = it.Current.Value;

            XPathNodeIterator cached = XPathCache.SelectSorted(
                expr, Document.CreateNavigator(),
                "mvp:price", XmlSortOrder.Ascending, XmlCaseOrder.LowerFirst, String.Empty, XmlDataType.Number,
                new XmlPrefix(Globals.MvpPrefix, Globals.MvpNamespace, Document.CreateNavigator().NameTable));

            DebugUtils.XPathNodeIteratorToConsole(cached);

            cached = XPathCache.SelectSorted(
                expr, Document.CreateNavigator(),
                "mvp:price", XmlSortOrder.Ascending, XmlCaseOrder.LowerFirst, String.Empty, XmlDataType.Number,
                new XmlPrefix(Globals.MvpPrefix, Globals.MvpNamespace, Document.CreateNavigator().NameTable));

            cached.MoveNext();
            cached.Current.MoveToFirstChild();
            string id2 = cached.Current.Value;

            Assert.AreEqual(id1, id2);
        }
Example #11
0
 /// <summary>
 /// Apply an XPath to a nodeset
 /// </summary>
 /// <param name="xpathSpec">The XPath to apply</param>
 /// <param name="doc">The nodeset context</param>
 /// <returns>A list of selected nodes</returns>
 public virtual NodeList applyTo(System.String xpathSpec, IList nodeSet)
 {
     //RuntimeSingleton.info("XPathTool::applyTo(String, List)");
     return(new NodeList(XPathCache.getXPath(xpathSpec).applyTo(nodeSet), false));
 }
Example #12
0
 /// <summary>
 /// Apply an XPath to a JDOM Element
 /// </summary>
 /// <param name="xpathSpec">The XPath to apply</param>
 /// <param name="doc">The Element context</param>
 /// <returns>A list of selected nodes</returns>
 public virtual NodeList applyTo(System.String xpathSpec, XmlElement elem)
 {
     //RuntimeSingleton.info("XPathTool::applyTo(String, Element)");
     return(new NodeList(XPathCache.getXPath(xpathSpec).applyTo(elem), false));
 }
Example #13
0
        public string CallAction(string action, string input, IProgressCallback progressReporter)
        {
            XmlNode     fault;
            XmlDocument outputDoc = null;
            var         inputDoc  = new XmlDocument();

            inputDoc.LoadXml(input);
            if (_userInfo == null)
            {
                _userInfo = _inn.applyAML(string.Format("<AML><Item type='User' action='get' select='default_vault' expand='1'><id>{0}</id><Relationships><Item type='ReadPriority' action='get' select='priority, related_id' expand='1' orderBy='priority'/></Relationships></Item></AML>", _inn.getUserID()));
            }

            if (action == "ApplyItem" || action == "ApplyAML")
            {
                var     fileNodes = XPathCache.SelectNodes("descendant-or-self::Item[@type='File' and (@action='add' or @action='update' or @action='create') and actual_filename]", inputDoc.DocumentElement);
                XmlNode locatedNode;
                if (fileNodes.Count > 0)
                {
                    Item fileItem = _inn.newItem();
                    foreach (var fileNode in fileNodes.OfType <XmlElement>())
                    {
                        if (string.IsNullOrEmpty(fileNode.Attribute("id")))
                        {
                            fileNode.Attr("id", _inn.getNewID());
                        }
                        fileNode.Elem("checkedout_path", Path.GetDirectoryName(fileNode.Element("actual_filename", "")));
                        fileNode.Elem("filename", Path.GetFileName(fileNode.Element("actual_filename", "")));
                        locatedNode = XPathCache.SelectSingleNode("Relationships/Item[@type='Located']/related_id", fileNode);
                        if (locatedNode == null)
                        {
                            fileItem.dom      = inputDoc;
                            fileItem.node     = (XmlElement)fileNode;
                            fileItem.nodeList = null;
                            fileItem.attachPhysicalFile(fileNode.Element("actual_filename", ""), _userInfo.getProperty("default_vault"));
                        }
                    }

                    var firstItem = XPathCache.SelectSingleNode("//Item[1]", inputDoc.DocumentElement);
                    IList <XmlElement> items;
                    if (firstItem.ParentNode == null)
                    {
                        items = new XmlElement[] { (XmlElement)firstItem };
                    }
                    else
                    {
                        items = firstItem.Parent().Elements("Item").ToList();
                    }

                    Item       result;
                    XmlElement resultNode = null;

                    for (var i = 0; i < items.Count; i++)
                    {
                        fileItem.dom      = items[i].OwnerDocument;
                        fileItem.node     = items[i];
                        fileItem.nodeList = null;
                        result            = fileItem.apply();
                        fault             = XPathCache.SelectSingleNode(faultXPath, result.dom.DocumentElement);
                        if (fault != null)
                        {
                            fault.AppendChild(result.dom.CreateElement("original_query")).InnerText = input;
                            return(result.dom.DocumentElement.OuterXml);
                        }
                        else if (result.isError())
                        {
                            throw new InvalidOperationException();
                        }

                        if (outputDoc == null)
                        {
                            outputDoc  = result.dom;
                            resultNode = XPathCache.SelectSingleNode("//Item[1]", outputDoc.DocumentElement).Parent() as XmlElement;
                        }
                        else
                        {
                            resultNode.AppendChild(outputDoc.ImportNode(result.node, true));
                        }

                        if (progressReporter != null)
                        {
                            progressReporter.ReportProgress(i + 1, items.Count);
                        }
                    }

                    return(outputDoc.OuterXml);
                }
            }

            outputDoc = new XmlDocument();
            outputDoc.Elem("Empty");
            _inn.getConnection().CallAction(action, inputDoc, outputDoc);
            fault = XPathCache.SelectSingleNode(faultXPath, outputDoc.DocumentElement);
            if (fault != null)
            {
                fault.AppendChild(outputDoc.CreateElement("original_query")).InnerText = input;
            }
            return(outputDoc.DocumentElement.OuterXml);
        }
Example #14
0
 public static IEnumerable <XmlNode> XPath(this XmlNode node, string xPath, params object[] vars)
 {
     return(XPathCache.SelectNodes(xPath, node,
                                   vars.Select((v, i) => new XPathVariable("p" + i.ToString(), v)).ToArray())
            .OfType <XmlNode>());
 }
Example #15
0
 public static IEnumerable <XmlNode> XPath(this XmlNode node, string xPath)
 {
     return(XPathCache.SelectNodes(xPath, node).OfType <XmlNode>());
 }
 public override XPathNodeIterator Evaluate(XPathNavigator doc,
                                            XmlNamespaceManager nm)
 {
     return(XPathCache.Select(XPath, doc, nm));
 }