Beispiel #1
0
        /// <summary>
        /// Gets the connection string.
        /// </summary>
        /// <param name="connectionString">A <see cref="string" /> containing the connection string.</param>
        /// <returns>
        /// Returns true if the connection string was fetched successfully.
        /// </returns>
        public bool TryGetConnectionString(out string connectionString)
        {
            connectionString = null;
            FileStream fs = null;

            try
            {
                fs = new FileStream(this.xmlFilePath, FileMode.Open, FileAccess.Read);
                XPathDocument   document  = new XPathDocument(fs);
                XPathNavigator  navigator = document?.CreateNavigator();
                XPathExpression query     = navigator?.Compile(this.xPath);

                object evaluatedObject = navigator?.Evaluate(query);
                connectionString = evaluatedObject as string;
                if (connectionString == null)
                {
                    var iterator = evaluatedObject as XPathNodeIterator;
                    if (iterator?.MoveNext() == true)
                    {
                        connectionString = iterator.Current?.Value;
                    }
                }

                return(connectionString != null);
            }
            catch (Exception)
            {
                Trace.TraceInformation($"Could not fetch the connection string from the file {this.xmlFilePath} with the XPath {this.xPath}.");
                return(false);
            }
            finally
            {
                fs?.Dispose();
            }
        }
Beispiel #2
0
    public XRDParser(Stream xrd)
    {
        doc_ = new XPathDocument (xrd);
        result_ = new XRDDocument ();
        cursor_ = doc_.CreateNavigator();

        expires_exp_ = cursor_.Compile ("/XRD/Expires");
        subject_exp_ = cursor_.Compile ("/XRD/Subject");
        aliases_exp_ = cursor_.Compile ("/XRD/Alias");
        types_exp_ = cursor_.Compile ("/XRD/Type");

        link_rel_exp_ = cursor_.Compile ("/XRD/Link/Rel");
        link_uri_exp_ = cursor_.Compile ("/XRD/Link/URI");
        link_mediatype_exp_ = cursor_.Compile ("/XRD/Link/MediaType");
    }
Beispiel #3
0
        /// <summary>
        /// Get the collection of Emails from the Http response stream
        /// </summary>
        /// <param name="stream">Response Stream</param>
        /// <returns>Collection of Emails</returns>
        public static List <Email> GetEmailCollection(Stream stream, out string nextChunkId)
        {
            List <Email> list        = new List <Email>();
            const string xpathSelect = @"//at:entry";

            StreamReader  reader    = new StreamReader(stream);
            XmlTextReader xmlreader = new XmlTextReader(reader);
            XPathDocument doc       = new XPathDocument(xmlreader);

            // initialize navigator
            XPathNavigator pn = doc.CreateNavigator();

            // initialize namespace manager
            XmlNamespaceManager resolver = new XmlNamespaceManager(pn.NameTable);

            resolver.AddNamespace("at", AtomNamespace);
            resolver.AddNamespace("cc", ConstantNamespace);

            XPathExpression expr = pn.Compile(xpathSelect);

            expr.SetContext(resolver);

            XPathNodeIterator nodes = pn.Select(expr);

            while (nodes.MoveNext())
            {
                // save current node
                XPathNavigator node = nodes.Current;

                // add Emai object to the collection
                list.Add(GetEmail(node, resolver));
            }

            nextChunkId = GetNextLink(pn, resolver);

            reader.Close();
            xmlreader.Close();

            return(list);
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            var            document  = new XPathDocument("2.xml");
            XPathNavigator navigator = document.CreateNavigator();

            Console.WriteLine("navigator.CanEdit = {0}", navigator.CanEdit);

            XPathNodeIterator iterator1 = navigator.Select("ListOfBooks/Book/Title");

            while (iterator1.MoveNext())
            {
                Console.WriteLine(iterator1.Current);
            }
            Console.WriteLine(new string('-', 19));
            XPathExpression   expr      = navigator.Compile("ListOfBooks/Book[2]/Price");
            XPathNodeIterator iterator2 = navigator.Select(expr);

            while (iterator2.MoveNext())
            {
                Console.WriteLine(iterator2.Current);
            }

            var xmldoc = new XmlDocument();

            xmldoc.Load("2.xml");

            navigator = xmldoc.CreateNavigator();
            navigator.MoveToChild("ListOfBooks", "");
            navigator.MoveToChild("Book", "");

            navigator.InsertBefore("<InsertBefore>insert_before</InsertBefore>");
            navigator.InsertAfter("<InsertAfter>insert_after</InsertAfter>");
            navigator.AppendChild("<AppendChild>append_child</AppendChild>");

            navigator.MoveToNext("Book", "");
            navigator.InsertBefore("<InsertBefore>111</InsertBefore>");
            navigator.InsertAfter("<InsertAfter>222</InsertAfter>");
            navigator.AppendChild("<AppendChild>333</AppendChild>");
            xmldoc.Save("2.xml");
        }
Beispiel #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="iteratorSport"></param>
        /// <returns></returns>
        private ISport SportPinnacleParse(String urlPathLeague, String urlPathFeed, XPathNodeIterator iteratorSport)
        {
            ISport         _sport = new Sport();
            XPathNavigator _sportNameNavigator = iteratorSport.Current.Clone();
            int            feedContentSport    = Convert.ToInt32(_sportNameNavigator.GetAttribute("feedContents", ""));

            if (feedContentSport > 0)
            {
                // ISport _sport = new Sport();
                _sport.ID   = Convert.ToInt32(_sportNameNavigator.GetAttribute("id", ""));
                _sport.Name = _sportNameNavigator.Value;

                //Add sport to List
                // sports.Add(_sport);
                //league- event
                XmlTextReader readerLeague = new XmlTextReader(string.Format(urlPathLeague, _sport.ID));
                readerLeague.WhitespaceHandling = WhitespaceHandling.Significant;
                XPathDocument  docLeague = new XPathDocument(readerLeague, XmlSpace.Preserve);
                XPathNavigator navLeague = docLeague.CreateNavigator();

                XPathExpression exprLeague;
                exprLeague = navLeague.Compile("/rsp/leagues/league");
                XPathNodeIterator iteratorLeague = navLeague.Select(exprLeague);
                // Loop all Leagues in each sport
                while (iteratorLeague.MoveNext())
                {
                    ILeague _league = LeaguePinnacleParse(urlPathFeed, _sport.ID, _sportNameNavigator, iteratorLeague);
                    if (_sport.Leagues == null)
                    {
                        _sport.Leagues = new List <ILeague>();
                    }
                    //check league not null
                    if (_league != null)
                    {
                        _sport.Leagues.Add(_league);
                    }
                }
            }
            return(_sport);
        }
        public static List <string> TrataRetorno(string aXml, string aTag, TipoRetorno aTipoRetorno)
        {
            List <string> retorno = new List <string>();

            XmlDocument _xml = new XmlDocument();

            _xml.LoadXml(aXml);
            XPathNavigator nav = _xml.CreateNavigator();

            XPathExpression expr;

            expr = nav.Compile("//*");
            XPathNodeIterator iterator = nav.Select(expr);

            try
            {
                while (iterator.MoveNext())
                {
                    XPathNavigator nav2 = iterator.Current.Clone();
                    if (nav2.Name == aTag)
                    {
                        if (aTipoRetorno == TipoRetorno.Codigo)
                        {
                            retorno.Add(nav2.Value);
                        }
                        else
                        {
                            //retorno.Add(new Erro(int.Parse(nav2.Value)).Instrucao);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(retorno);
        }
        static void Main(string[] args)
        {
            PerfTest perf   = new PerfTest();
            int      repeat = 1000;

            perf.Start();
            XPathDocument doc = new XPathDocument(Globals.GetResource(Globals.NorthwindResource));

            //XmlDocument doc = new XmlDocument();
            //doc.Load("test/northwind.xml");
            Console.WriteLine("Loading XML document: {0, 6:f2} ms", perf.Stop());
            XPathNavigator  nav  = doc.CreateNavigator();
            XPathExpression expr = nav.Compile("/ROOT/CustomerIDs/OrderIDs/Item[OrderID=' 10330']/ShipAddress");

            Console.WriteLine("Regular selection, warming...");
            SelectNodes(nav, repeat, perf, expr);
            Console.WriteLine("Regular selection, testing...");
            SelectNodes(nav, repeat, perf, expr);


            perf.Start();
            IndexingXPathNavigator inav = new IndexingXPathNavigator(
                doc.CreateNavigator());

            Console.WriteLine("Building IndexingXPathNavigator: {0, 6:f2} ms", perf.Stop());
            perf.Start();
            inav.AddKey("orderKey", "OrderIDs/Item", "OrderID");
            Console.WriteLine("Adding keys: {0, 6:f2} ms", perf.Stop());
            XPathExpression expr2 = inav.Compile("key('orderKey', ' 10330')/ShipAddress");

            perf.Start();
            inav.BuildIndexes();
            Console.WriteLine("Indexing: {0, 6:f2} ms", perf.Stop());

            Console.WriteLine("Indexed selection, warming...");
            SelectIndexedNodes(inav, repeat, perf, expr2);
            Console.WriteLine("Indexed selection, testing...");
            SelectIndexedNodes(inav, repeat, perf, expr2);
        }
Beispiel #8
0
        private string parseXPath(string xPath)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                if (_xPathDocument != null)
                {
                    XPathNavigator  navigator  = _xPathDocument.CreateNavigator();
                    XPathExpression expression = navigator.Compile(xPath);

                    XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());

                    foreach (DictionaryEntry de in _namespaces)
                    {
                        xnm.AddNamespace((string)de.Key, (string)de.Value);
                    }

                    expression.SetContext(xnm);

                    XPathNodeIterator xni = navigator.Select(expression);

                    sb.AppendFormat("Count: [{0}]", xni.Count);
                    sb.AppendLine();
                    while (xni.MoveNext())
                    {
                        sb.AppendFormat("[{0}] - {1}", xni.CurrentPosition, xni.Current.OuterXml);
                        sb.AppendLine();
                    }
                }
            }
            catch (Exception ex)
            {
                sb.Append(ex.Message);
                sb.AppendLine();
            }

            return(sb.ToString());
        }
Beispiel #9
0
        public static string XMLReportQuery(string className, string ApplicationPath)
        {
            string PathFile   = string.Empty;
            string NameOfFile = string.Empty;
            string strXML     = string.Empty;
            string lClassName = "ClassName";

            System.Configuration.AppSettingsReader appconfig = new System.Configuration.AppSettingsReader();
            NameOfFile = appconfig.GetValue("ConfigurationOfReports", typeof(string)) as string;

            PathFile = Path.GetFullPath(NameOfFile);
            if (!File.Exists(PathFile))
            {
                if (!File.Exists(PathFile))
                {
                    throw (new ArgumentException("File not found: " + PathFile));
                }
            }

            XmlDocument lxmlDoc = new XmlDocument();

            lxmlDoc.Load(PathFile);

            //Open the document and associate a navigator.
            XPathNavigator navXPath = lxmlDoc.CreateNavigator();

            string xpathQuery;             //@"XMLReportQuery/@Name[text() = '" +XMLReportQueryName + "']";

            //Select nodes with the same class name.
            xpathQuery = @"/XMLReportsQuery/XMLReportQuery[@" + lClassName + " = '" + className.Trim() + "']";

            XPathExpression expXPath = navXPath.Compile(xpathQuery);

            //Order the reports by the type of report.
            expXPath.AddSort("@Type", XmlSortOrder.Ascending, XmlCaseOrder.None, string.Empty, XmlDataType.Text);
            XPathNodeIterator itNodes = navXPath.Select(expXPath);

            return(XMLReportsQueryHandler.GetOutXML(itNodes.Clone()));
        }
Beispiel #10
0
        /// <summary>
        /// Récupère la valeur de l'attribut du noeud recherché dans le fichier de configuration
        /// </summary>
        /// <param name="xPathString">Expression XPath de recherche du noeud</param>
        /// <param name="attribute">Attribut à rechercher</param>
        /// <returns>Une ArrayList contenant la liste des attributs recherchés</returns>
        public List <string> GetAttributes(string xPathString, string attribute)
        {
            // Initilisation des variables
            XPathNodeIterator xpathNodeIterator;
            XPathExpression   expr;

            List <string> attributes = new List <string>();

            // Parcours du fichier XML
            xpathNavigator    = xpathDoc.CreateNavigator();
            expr              = xpathNavigator.Compile(xPathString);
            xpathNodeIterator = xpathNavigator.Select(expr);

            while (xpathNodeIterator.MoveNext())
            {
                // On récupère l'attribut
                attributes.Add(xpathNodeIterator.Current.GetAttribute(attribute, ""));
            }


            return(attributes);
        }
        //регистронезависимый поиск
        public void FindOrganizationName(string prefix, string suggestion)
        {
            //XPath = string.Format("*//Address/State[compare(string(.),'{0}')]", nodename);
            string xpathcommand = string.Format("{0}[compare(string(.),'{1}')]", prefix, suggestion);

            // Create an XPathExpression
            XPathExpression exp = xpathnav.Compile(xpathcommand);

            // Set the context to resolve the function
            // ResolveFunction is called at this point
            exp.SetContext(ctx);

            // Select nodes based on the XPathExpression
            // IXsltContextFunction.Invoke is called for each
            // node to filter the resulting nodeset
            XPathNodeIterator nodes = xpathnav.Select(exp);

            foreach (XPathNavigator node in nodes)
            {
                // Do something...
            }
        }
        /// <summary>
        /// Get Email Campaign from the Http response stream.
        /// </summary>
        /// <param name="stream">Response stream</param>
        /// <returns>Email Campaign</returns>
        public static EmailCampaign GetEmailCampaign(Stream stream)
        {
            EmailCampaign campaign    = new EmailCampaign();
            const string  xpathSelect = @"//at:entry";

            StreamReader  reader    = new StreamReader(stream);
            XmlTextReader xmlreader = new XmlTextReader(reader);
            XPathDocument doc       = new XPathDocument(xmlreader);

            // initialize navigator
            XPathNavigator pn = doc.CreateNavigator();

            // initialize namespace manager
            XmlNamespaceManager resolver = new XmlNamespaceManager(pn.NameTable);

            resolver.AddNamespace("at", AtomNamespace);
            resolver.AddNamespace("cc", ConstantNamespace);

            XPathExpression expr = pn.Compile(xpathSelect);

            expr.SetContext(resolver);

            XPathNodeIterator nodes = pn.Select(expr);

            while (nodes.MoveNext())
            {
                // save current node
                XPathNavigator node = nodes.Current;

                // add Contact List object to the collection
                campaign = GetEmailCampaign(node, resolver);
                break;
            }

            reader.Close();
            xmlreader.Close();

            return(campaign);
        }
Beispiel #13
0
        /// <summary>
        /// Lis le fichier xml dédié pour retourner la liste des clones - Read dedicated xml file to get the list of clones
        /// </summary>
        /// <param name="lGames"></param>
        internal void ListClones(List <Clone> lClones, string ID)
        {
            XPathNavigator    nav   = _XDoc.CreateNavigator();
            XPathNodeIterator nodes = nav.Select(nav.Compile($"//LaunchBox/AdditionalApplication[GameID='{ID}']"));

            if (nodes.Count != 0)
            {
                while (nodes.MoveNext())
                {
                    Console.WriteLine(nodes.Current.Name);
                    nodes.Current.MoveToFirstChild();

                    Clone zeClone = new Clone();

                    do
                    {
                        switch (nodes.Current.Name)
                        {
                        case "ApplicationPath":
                            Console.WriteLine(nodes.Current.Value);
                            zeClone.ApplicationPath = nodes.Current.Value;
                            break;

                        case "GameID":
                            Console.WriteLine(nodes.Current.Value);
                            zeClone.GameID = nodes.Current.Value;
                            break;

                        case "Id":
                            Console.WriteLine(nodes.Current.Value);
                            zeClone.Id = nodes.Current.Value;
                            break;
                        }
                    } while (nodes.Current.MoveToNext());

                    lClones.Add(zeClone);
                }
            }
        }
Beispiel #14
0
    // Returns the relative path to the icon file
    // @todo make non-static, nav as member
    public static string GetPathFromNode(string sheet, string objectname,
                                         XPathNavigator nav)
    {
        XmlNamespaceManager manager = new XmlNamespaceManager(nav.NameTable);

        manager.AddNamespace("dia",
                             "http://www.lysator.liu.se/~alla/dia/dia-sheet-ns");

        XPathExpression iconquery =
            nav.Compile("/dia:sheet/dia:contents/dia:object[@name='" + objectname +
                        "']/dia:icon");

        iconquery.SetContext(manager);
        XPathNodeIterator objectdescriptions = nav.Select(iconquery);

        while (objectdescriptions.MoveNext())
        {
            return(objectdescriptions.Current.Value);
        }

        return(GetPathFromObjectName(sheet, objectname));
    }
Beispiel #15
0
        public void OldFrameworkXPathBugIsFixed()
        {
            // see http://bytes.com/topic/net/answers/177129-reusing-xpathexpression-multiple-iterations
            var doc = new XmlDocument();

            doc.LoadXml("<root><a><a1/><a2/></a><b/></root>");

            XPathNavigator  nav  = doc.CreateNavigator();
            XPathExpression expr = nav.Compile("*");

            nav.MoveToFirstChild(); // root
            XPathNodeIterator iter1 = nav.Select(expr);

            iter1.MoveNext(); // root/a
            XPathNodeIterator iter2 = iter1.Current.Select(expr);

            iter2.MoveNext(); // /root/a/a1
            iter2.MoveNext(); // /root/a/a2

            // used to fail because iter1 and iter2 would conflict
            Assert.IsTrue(iter1.MoveNext()); // root/b
        }
Beispiel #16
0
        private static string GetObjectLoadScript()
        {
            Assembly        a      = Assembly.GetExecutingAssembly();
            string          path   = Path.Combine(a.Location, "Objects.xml");
            Stream          stream = a.GetManifestResourceStream("OpenCBS.Test._Sql.Objects.xml");
            XPathDocument   xmldoc = new XPathDocument(stream);
            XPathNavigator  nav    = xmldoc.CreateNavigator();
            XPathExpression expr   = nav.Compile("/database/object");

            expr.AddSort("@priority", XmlSortOrder.Ascending, XmlCaseOrder.None, null, XmlDataType.Number);
            XPathNodeIterator iterator = nav.Select(expr);

            string retval = string.Empty;

            while (iterator.MoveNext())
            {
                XPathNavigator create = iterator.Current.SelectSingleNode("create");
                XPathNavigator drop   = iterator.Current.SelectSingleNode("drop");
                retval += string.Format("{0}\r\nGO\r\n\r\n{1}\r\nGO\r\n\r\n", drop.Value, create.Value);
            }
            return(retval);
        }
Beispiel #17
0
        public static void ReadXPath()
        {
            var            document  = new XPathDocument("books.xml");
            XPathNavigator navigator = document.CreateNavigator();

            XPathNodeIterator iterator1 = navigator.Select("ListOfBooks/Book/Title");

            foreach (var item in iterator1)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine(new string('-', 40));

            XPathExpression   expr      = navigator.Compile("ListOfBooks/Book[2]/Price");
            XPathNodeIterator iterator2 = navigator.Select(expr);

            foreach (var item in iterator2)
            {
                Console.WriteLine(item);
            }
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            double sum = 0;

            XPathDocument  document  = new XPathDocument("books.xml");
            XPathNavigator navigator = document.CreateNavigator();

            XPathExpression expression = navigator.Compile("sum(ListOfBooks/Book/Price/text())");

            Console.WriteLine(expression.ReturnType);

            if (expression.ReturnType == XPathResultType.Number)
            {
                sum = (double)navigator.Evaluate(expression);
                Console.WriteLine(sum);
            }

            sum = (double)navigator.Evaluate("sum(//Price/text())*10");
            Console.WriteLine(sum);

            Console.ReadKey();
        }
Beispiel #19
0
        /**
         *
         */

        private string GetTPSName()
        {
            string         tpsiName = null;
            Stream         stream   = new MemoryStream(_content);
            var            doc      = new XPathDocument(stream);
            XPathNavigator nav      = doc.CreateNavigator();

            nav.MoveToFollowing(XPathNodeType.Element);
            IDictionary <string, string> namespaces = nav.GetNamespacesInScope(XmlNamespaceScope.All);
            XPathExpression query = nav.Compile("/tpsi:CASS_MTPSI/tpsi:CASS_MTPSI_page/tpsi:UUT/tpsi:UUT_ID");
            var             mngr  = new XmlNamespaceManager(new NameTable());

            foreach (var nskvp in namespaces)
            {
                mngr.AddNamespace(nskvp.Key, nskvp.Value);
                if (nskvp.Key == "")
                {
                    mngr.AddNamespace("tpsi", nskvp.Value);
                }
            }
            //mngr.AddNamespace("bk", "urn:MyNamespace");
            query.SetContext(mngr);
            XPathNodeIterator xPathIt = nav.Select(query);

            if (xPathIt.Count > 0)
            {
                if (xPathIt.MoveNext())
                {
                    XPathNavigator curNav = xPathIt.Current;
                    if (curNav.HasAttributes)
                    {
                        tpsiName = curNav.GetAttribute("TPS_Name", "");
                        LogManager.SourceTrace(SOURCE, "TPS Name: " + tpsiName);
                    }
                }
            }
            return(tpsiName);
        }
Beispiel #20
0
        public static void CheckOut()
        {
            //Enregistrement de la position de la voiture rendue par le client
            //Identification de la voiture utilisée par le client
            XPathDocument  doc = new XPathDocument("M3.xml");
            XPathNavigator nav = doc.CreateNavigator();

            XPathExpression expr;
            string          requeteXpath = "/messageClient";

            expr = nav.Compile(requeteXpath);

            XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath

            //parcourir le resultat
            //---------------------
            string immatVoiture = "";
            string idSejour     = "";
            string idClient     = "";

            while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud)
            {
                idClient     = nodes.Current.SelectSingleNode("IDClient").InnerXml;
                immatVoiture = nodes.Current.SelectSingleNode("immatriculation").InnerXml;
                idSejour     = nodes.Current.SelectSingleNode("IDSejour").InnerXml;
            }
            //On affiche les informations concernant la voiture rendue
            Console.WriteLine("Voici les informations de la voiture utilisé par le client " + idClient);
            ExecuterUneCommandeSQLStr("select distinct Vehicule_Immatriculation,StatutDispo ,NomParking, PlaceParking from Stationne as S natural join Vehicule as V natural join Parking as P where S.Parking_Arrondissement=P.Arrondissement and Vehicule_Immatriculation=Immatriculation and Vehicule_Immatriculation = \u0022" + immatVoiture + "\u0022;");

            Console.WriteLine("On ajoute un entretien a faire à la voiture");
            string idEntretien = creationIDEntretien();

            ExecuterUneCommandeSQLStr("INSERT INTO `Entretien` (`IDentretien`, `Vehicule_Immatriculation`, `Controleur_IDControleur`, `Motif`, `DateEntretien`) VALUES ('" + idEntretien + "', '" + immatVoiture + "', 'C01', 'Nettoyage', '12.01.18');");
            ExecuterUneCommandeSQLStr("update Vehicule set MotifStatut = \u0022Nettoyage\u0022 where Immatriculation = \u0022" + immatVoiture + "\u0022;");
            Console.WriteLine("On remet la voiture en service après l'entretien");
            ExecuterUneCommandeSQLStr("update Vehicule set StatutDispo = 0 and MotifStatut = \u0022\u0022 where Immatriculation = \u0022" + immatVoiture + "\u0022;");
        }
        /// <summary>
        /// Retrieve an Individual Contact List from the Http response stream
        /// </summary>
        /// <param name="stream">Reponse Stream</param>
        /// <returns>Contact List parsed from the reponse Stream</returns>
        public static ContactList GetContactListDetails(Stream stream)
        {
            ContactList  cList       = null;
            const string xpathSelect = @"//cc:ContactList";

            StreamReader  reader    = new StreamReader(stream);
            XmlTextReader xmlreader = new XmlTextReader(reader);
            XPathDocument doc       = new XPathDocument(xmlreader);

            // initialize navigator
            XPathNavigator pn = doc.CreateNavigator();

            // initialize namespace manager
            XmlNamespaceManager resolver = new XmlNamespaceManager(pn.NameTable);

            resolver.AddNamespace("at", AtomNamespace);
            resolver.AddNamespace("cc", ConstantNamespace);

            XPathExpression expr = pn.Compile(xpathSelect);

            expr.SetContext(resolver);

            XPathNodeIterator nodes = pn.Select(expr);

            while (nodes.MoveNext())
            {
                // save current node
                XPathNavigator node = nodes.Current;

                // get the Contact List object
                cList = GetContactList(node, resolver);
            }

            reader.Close();
            xmlreader.Close();

            return(cList);
        }
Beispiel #22
0
        /// <summary>
        ///     Get the output of running the XPath expression on the input nodes
        /// </summary>
        public override object GetOutput()
        {
            XmlDSigNodeList outputNodes = new XmlDSigNodeList();

            // Only do work if we've been loaded with both an XPath expression as well as a list of input
            // nodes to transform
            if (m_xpathExpression != null && m_inputNodes != null)
            {
                XPathNavigator navigator = m_inputNodes.CreateNavigator();

                // Build up an expression for the XPath the transform specified and hook up the namespace
                // resolver which will resolve namsepaces against the original XPath expression's XML context.
                XPathExpression transformExpression = navigator.Compile(
                    String.Format(CultureInfo.InvariantCulture, "boolean({0})", m_xpathExpression));

                // Get the namespaces into scope for use in the expression
                XmlNamespaceManager namespaceManager = new XmlNamespaceManager(m_inputNodes.NameTable);
                foreach (KeyValuePair <string, string> namespaceDeclaration in m_namespaces)
                {
                    namespaceManager.AddNamespace(namespaceDeclaration.Key, namespaceDeclaration.Value);
                }
                transformExpression.SetContext(namespaceManager);

                // Iterate over the input nodes, applying the XPath expression to each.  If the XPath
                // expression returns true for the node, then add it to the output NodeList
                XPathNodeIterator inputNodeIterator = navigator.Select("//. | //@*");
                while (inputNodeIterator.MoveNext())
                {
                    XPathNavigator current = inputNodeIterator.Current;
                    if ((bool)current.Evaluate(transformExpression))
                    {
                        outputNodes.Add((current as IHasXmlNode).GetNode());
                    }
                }
            }

            return(outputNodes);
        }
Beispiel #23
0
        static void Exo1()
        {
            string nomDuDocXML = "bdtheque.xml";

            //créer l'arborescence des chemins XPath du document
            //--------------------------------------------------
            XPathDocument  doc = new System.Xml.XPath.XPathDocument(nomDuDocXML);
            XPathNavigator nav = doc.CreateNavigator();

            //créer une requete XPath
            //-----------------------
            string          maRequeteXPath = "/bdtheque/BD";
            XPathExpression expr           = nav.Compile(maRequeteXPath);

            //exécution de la requete
            //-----------------------
            XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath

            //parcourir le resultat
            //---------------------

            while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud BD)
            {
                string titre  = nodes.Current.SelectSingleNode("titre").InnerXml;
                string auteur = ", écrit par " + nodes.Current.SelectSingleNode("auteur").InnerXml;
                string isbn   = ", Numéro ISBN : " + nodes.Current.GetAttribute("isbn", "");

                string pages = "";
                if (nodes.Current.SelectSingleNode("nombre_pages") != null)
                {
                    pages = " (" + nodes.Current.SelectSingleNode("nombre_pages").InnerXml + " pages)";
                }
                Console.WriteLine(titre + pages + auteur + isbn);

                Console.WriteLine("");
                // a compléter
            }
        }
Beispiel #24
0
        /// <summary>
        /// Deleted the specified nodes in XPath
        /// </summary>
        private void RemoveMarkupNodesFromMarkupDocument(XPathNavigator navigator, string xpath)
        {
            if (navigator.NameTable == null)
            {
                return;
            }
            var xmlNamespaceManger = new XmlNamespaceManager(navigator.NameTable);

            //SET THE XMLNS WITH XPATH EXPRESSION
            xmlNamespaceManger.AddNamespace(Constants.XmlNamespacePrefix, Constants.XmlNamespace);
            var xpathExpression = navigator.Compile(xpath);

            xpathExpression.SetContext(xmlNamespaceManger);

            var nodeIterator = navigator.Select(xpathExpression);

            //Delete the nodes
            while (nodeIterator.MoveNext())
            {
                nodeIterator.Current.DeleteSelf();
                nodeIterator = navigator.Select(xpathExpression);
            }
        }
        static string RecuperationNom()
        {
            string nomClient = "";

            XPathDocument  doc = new XPathDocument("M1.xml");
            XPathNavigator nav = doc.CreateNavigator();

            //créer une requete XPath

            string          maRequeteXPath = "/Client/Nom";
            XPathExpression expr           = nav.Compile(maRequeteXPath);

            //exécution de la requete

            XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath

            while (nodes.MoveNext())
            {
                nomClient = nodes.Current.Value;
            }

            return(nomClient);
        }
Beispiel #26
0
        protected XPathExpression CompileXPathExpression(string e, XPathNavigator context, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
        {
            CallerInformation caller = new CallerInformation(memberName, fileName, lineNumber);

            XPathExpression expr;

            try
            {
                expr = context.Compile(e);
            }
            catch (XPathException xpe)
            {
                Error(xpe, "Could not compile XPath expression {0}.", e);
                return(null);
            }
            catch (ArgumentException ae)
            {
                Error(ae, "Could not compile XPath expression {0}.", e);
                return(null);
            }
            Debug("XPath expression {0} has type {1}.", e, expr.ReturnType.ToString());
            return(expr);
        }
        public SettingsManager(Game XnaGame)
            : base(XnaGame)
        {
            this.Game.Components.Add(this);
            string Data = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Data\\Settings.xml");

            System.IO.MemoryStream _stream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(Data));

            XPathDocument   _doc = new XPathDocument(_stream);
            XPathNavigator  _nav = _doc.CreateNavigator();
            XPathExpression _expr;

            _expr = _nav.Compile("/game");

            XPathNodeIterator _Iter = _nav.Select(_expr);

            _Iter.MoveNext();

            var _Nav2 = _Iter.Current.Clone();

            Fonts      = _Nav2.SelectSingleNode("fonts").Value;
            WindowSize = _Nav2.SelectSingleNode("windowsize").Value;
        }
Beispiel #28
0
        public static XPathNodeIterator SelectNodes(XPathNavigator navigator, string xpath, ref XPathExpression compiledExpression, bool multiThreaded)
        {
            if (navigator == null)
            {
                throw new ArgumentNullException("navigator");
            }
            if (xpath == null)
            {
                throw new ArgumentNullException("xpath");
            }
            XPathExpression expression = compiledExpression;

            if (expression == null)
            {
                expression         = navigator.Compile(xpath);
                compiledExpression = expression;
            }
            else if (multiThreaded)
            {
                expression = expression.Clone();
            }
            return(navigator.Select(expression));
        }
Beispiel #29
0
    static void XPathNavigatorMethods_Matches()
    {
        //<snippet24>
        XPathDocument  document  = new XPathDocument("books.xml");
        XPathNavigator navigator = document.CreateNavigator();

        // Select all book nodes.
        XPathNodeIterator nodes = navigator.SelectDescendants("book", "", false);

        // Select all book nodes that have the matching attribute value.
        XPathExpression expr = navigator.Compile("book[@genre='novel']");

        while (nodes.MoveNext())
        {
            XPathNavigator navigator2 = nodes.Current.Clone();
            if (navigator2.Matches(expr))
            {
                navigator2.MoveToFirstChild();
                Console.WriteLine("Book title:  {0}", navigator2.Value);
            }
        }
        //</snippet24>
    }
Beispiel #30
0
        static string lectureXML(string chemin)
        {
            //créer l'arborescence des chemins XPath du document
            //--------------------------------------------------
            XPathDocument  doc = new XPathDocument("Message1.xml");
            XPathNavigator nav = doc.CreateNavigator();

            //créer une requete XPath

            string          maRequeteXPath = "/Client/Nom";
            XPathExpression expr           = nav.Compile(maRequeteXPath);

            //exécution de la requete

            XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath
            string            nom   = "";

            while (nodes.MoveNext())
            {
                nom = nodes.Current.Value;
            }
            return(nom);
        }
Beispiel #31
0
        private string[] GetErrorsFromResponse(string response)
        {
            ThrowIfContainsServerError(response);

            XPathDocument       doc   = new XPathDocument(new StringReader(response));
            XPathNavigator      nav   = doc.CreateNavigator();
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);

            nsmgr.AddNamespace("lm", LinkMe.Apps.Services.Constants.XmlSerializationNamespace);
            XPathExpression expr = nav.Compile("//lm:Error");

            expr.SetContext(nsmgr);
            XPathNodeIterator iter = nav.Select(expr);
            List <string>     res  = new List <string>();

            while (iter.MoveNext())
            {
                XPathNavigator node = iter.Current;
                res.Add(node.Value);
            }

            return(res.ToArray());
        }
    // Returns the relative path to the icon file
    // @todo make non-static, nav as member
    public static string GetPathFromNode(string sheet, string objectname,
					XPathNavigator nav)
    {
        XmlNamespaceManager manager = new XmlNamespaceManager (nav.NameTable);
        manager.AddNamespace ("dia",
              "http://www.lysator.liu.se/~alla/dia/dia-sheet-ns");

        XPathExpression iconquery =
          nav.Compile ("/dia:sheet/dia:contents/dia:object[@name='" + objectname +
           "']/dia:icon");
        iconquery.SetContext (manager);
        XPathNodeIterator objectdescriptions = nav.Select (iconquery);
        while (objectdescriptions.MoveNext ())
          {
        return objectdescriptions.Current.Value;
          }

        return GetPathFromObjectName (sheet, objectname);
    }