Beispiel #1
0
        public static void InsertJob(XDocument jobXml)
        {
            string username = jobXml.XPathSelectElement("data/username").Value;

            Console.WriteLine("Username: {0}", username);
            Console.WriteLine("Job type: {0}", jobXml.XPathSelectElement("data/").Value);
        }
        public string DrawRegistryDocument(XDocument xd)
        {
            string sHTML = "";
            if (xd.XPathSelectElement("registry") != null)
            {
                sHTML += "<div class=\"ui-widget-content ui-corner-bottom registry\">";
                sHTML += "  <div class=\"ui-state-default registry_section_header\" xpath=\"registry\">"; //header
                sHTML += "      <div class=\"registry_section_header_title\">Registry</div>";

                sHTML += "<div class=\"registry_section_header_icons\">"; //step header icons

                sHTML += "<span id=\"registry_refresh_btn\" class=\"pointer\">" +
                    "<img style=\"width:10px; height:10px;\" src=\"../images/icons/reload_16.png\"" +
                    " alt=\"\" title=\"Refresh\" /></span>";

                sHTML += "<span class=\"registry_node_add_btn pointer\"" +
                    " xpath=\"registry\">" +
                    "<img style=\"width:10px; height:10px;\" src=\"../images/icons/edit_add.png\"" +
                    " alt=\"\" title=\"Add another...\" /></span>";

                sHTML += "</div>";  //end step header icons
                sHTML += "  </div>"; //end header

                foreach (XElement xe in xd.XPathSelectElement("registry").Nodes())
                {
                    sHTML += DrawRegistryNode(xe, "registry/" + xe.Name.ToString());
                }

                sHTML += "</div>";
            }

            if (sHTML.Length == 0)
                sHTML = "Registry is empty.";
            return sHTML;
        }
Beispiel #3
0
		public static void Save(BlogPost post, string file) {
			post.LastModified = DateTime.UtcNow;

			XDocument doc = new XDocument(
				new XElement("post",
					new XElement("title", post.Title),
					new XElement("slug", post.Slug),
					new XElement("author", post.Author),
					new XElement("pubDate", post.PubDate.ToString("yyyy-MM-dd HH:mm:ss")),
					new XElement("lastModified", post.LastModified.ToString("yyyy-MM-dd HH:mm:ss")),
					new XElement("content", post.Content),
					new XElement("ispublished", post.IsPublished),
					new XElement("categories", string.Empty),
					new XElement("comments", string.Empty)
					));

			XElement categories = doc.XPathSelectElement("post/categories");
			foreach (string category in post.Categories) {
				categories.Add(new XElement("category", category));
			}

			XElement comments = doc.XPathSelectElement("post/comments");

			doc.Save(file);
		}
Beispiel #4
0
        public override void ModifyConfig(XDocument doc)
        {
            // Add the new audit config section, if the ForwardReceivedMessagesTo attribute has not been set in the UnicastBusConfig.
            var frmAttributeEnumerator = (IEnumerable)doc.XPathEvaluate("/configuration/UnicastBusConfig/@ForwardReceivedMessagesTo");
            var isForwardReceivedMessagesAttributeDefined = frmAttributeEnumerator.Cast<XAttribute>().Any();

            // Then add the audit config
            var sectionElement =
                doc.XPathSelectElement(
                    "/configuration/configSections/section[@name='AuditConfig' and @type='NServiceBus.Config.AuditConfig, NServiceBus.Core']");
            if (sectionElement == null)
            {
                if (isForwardReceivedMessagesAttributeDefined)
                    doc.XPathSelectElement("/configuration/configSections").Add(new XComment(exampleAuditConfigSection));
                else
                    doc.XPathSelectElement("/configuration/configSections").Add(new XElement("section",
                    new XAttribute("name",
                        "AuditConfig"),
                    new XAttribute("type",
                        "NServiceBus.Config.AuditConfig, NServiceBus.Core")));
            }

            var forwardingElement = doc.XPathSelectElement("/configuration/AuditConfig");
            if (forwardingElement == null)
            {
                doc.Root.LastNode.AddAfterSelf(new XComment(Instructions),
                    isForwardReceivedMessagesAttributeDefined ? (object) new XComment(@"Since we detected that you already have forwarding setup we haven't enabled the audit feature.
Please remove the ForwardReceivedMessagesTo attribute from the UnicastBusConfig and uncomment the AuditConfig section. 
<AuditConfig QueueName=""audit"" />") : new XElement("AuditConfig", new XAttribute("QueueName", "audit")));
            }

        }
 private void addElements (XDocument manifest, params string[] elements) {
     foreach (var element in elements) {
         if (null == manifest.XPathSelectElement(element, this)) {
             manifest.XPathSelectElement(getParentElement(element), this).Add(getElement(element));
         }
     }
 }
        public OutputPathMode GetProjectOutputMode(XDocument document)
        {
            var platformSpecificOutputFolderElement = document.XPathSelectElement("/Project/Properties/PlatformSpecificOutputFolder");
            var projectSpecificOutputFolderElement = document.XPathSelectElement("/Project/Properties/ProjectSpecificOutputFolder");
            var platformSpecificOutputFolder = true;
            var projectSpecificOutputFolder = false;

            if (platformSpecificOutputFolderElement != null)
            {
                platformSpecificOutputFolder = platformSpecificOutputFolderElement.Value.ToLowerInvariant() != "false";
            }
            if (projectSpecificOutputFolderElement != null)
            {
                projectSpecificOutputFolder = projectSpecificOutputFolderElement.Value.ToLowerInvariant() == "true";
            }

            var outputMode = OutputPathMode.BinConfiguration;
            if (projectSpecificOutputFolder)
            {
                outputMode = OutputPathMode.BinProjectPlatformArchConfiguration;
            }
            if (platformSpecificOutputFolder)
            {
                outputMode = OutputPathMode.BinPlatformArchConfiguration;
            }

            return outputMode;
        }
        public override void ModifyConfig(XDocument doc)
        {
            const string Instructions = @"<MessageForwardingInCaseOfFaultConfig 
    ErrorQueue=""The queue to which errors will be forwarded."" />";

            var sectionElement = doc.XPathSelectElement("/configuration/configSections/section[@name='MessageForwardingInCaseOfFaultConfig' and @type='NServiceBus.Config.MessageForwardingInCaseOfFaultConfig, NServiceBus.Core']");
            if (sectionElement == null)
            {

                doc.XPathSelectElement("/configuration/configSections").Add(new XElement("section",
                                                                                         new XAttribute("name",
                                                                                                        "MessageForwardingInCaseOfFaultConfig"),
                                                                                         new XAttribute("type",
                                                                                                        "NServiceBus.Config.MessageForwardingInCaseOfFaultConfig, NServiceBus.Core")));

            }

            var forwardingElement = doc.XPathSelectElement("/configuration/MessageForwardingInCaseOfFaultConfig");
            if (forwardingElement == null)
            {
                doc.Root.LastNode.AddAfterSelf(new XComment(Instructions), 
                                                new XElement("MessageForwardingInCaseOfFaultConfig",
                                                new XAttribute("ErrorQueue", "error")));
            }
        }
Beispiel #8
0
    // Can this be done async?
    public static void Save(Post post)
    {
        string file = Path.Combine(_folder, post.ID + ".xml");
        post.LastModified = DateTime.UtcNow;

        XDocument doc = new XDocument(
                        new XElement("post",
                            new XElement("title", post.Title),
                            new XElement("slug", post.Slug),
                            new XElement("author", post.Author),
                            new XElement("pubDate", post.PubDate.ToString("yyyy-MM-dd HH:mm:ss")),
                            new XElement("lastModified", post.LastModified.ToString("yyyy-MM-dd HH:mm:ss")),
                            new XElement("excerpt", post.Excerpt),
                            new XElement("content", post.Content),
                            new XElement("ispublished", post.IsPublished),
                            new XElement("categories", string.Empty),
                            new XElement("comments", string.Empty)
                        ));

        XElement categories = doc.XPathSelectElement("post/categories");
        foreach (string category in post.Categories)
        {
            categories.Add(new XElement("category", category));
        }

        XElement comments = doc.XPathSelectElement("post/comments");
        foreach (Comment comment in post.Comments)
        {
            comments.Add(
                new XElement("comment",
                    new XElement("author", comment.Author),
                    new XElement("email", comment.Email),
                    new XElement("website", comment.Website),
                    new XElement("ip", comment.Ip),
                    new XElement("userAgent", comment.UserAgent),
                    new XElement("date", comment.PubDate.ToString("yyyy-MM-dd HH:m:ss")),
                    new XElement("content", comment.Content),
                    new XAttribute("isAdmin", comment.IsAdmin),
                    new XAttribute("isApproved", comment.IsApproved),
                    new XAttribute("id", comment.ID)
                ));
        }

        if (!File.Exists(file)) // New post
        {
            var posts = GetAllPosts();
            posts.Insert(0, post);
            posts.Sort((p1, p2) => p2.PubDate.CompareTo(p1.PubDate));
            HttpRuntime.Cache.Insert("posts", posts);
        }
        else
        {
            Blog.ClearStartPageCache();
        }

        doc.Save(file);
    }
 public virtual bool Transform(XDocument document)
 {
     if (document == null) { return false; }
     var element = document.XPathSelectElement(this.Xpath);
     if (element == null)
     {
         return false;
     }
     var attribute = element.Attribute(this.AttributeName);
     if (attribute == null)
     {
         return false;
     }
     var path = Path.Combine(this.FilePath, attribute.Value);
     if (!File.Exists(path))
     {
         throw new Exception(string.Format("Cannot find {0}", path));
     }
     var root = XDocument.Load(path).Root;
     if (!element.ToString().Equals(root.ToString()))
     {
         element.ReplaceWith(root);
         return true;
     }
     return false;
 }
        private void SimpleWriting()
        {
            XDocument xd;
              XElement root;
              XElement child;

              xd =
            new XDocument(
              new XDeclaration("1.0", "utf-8", "yes"),
              new XComment("Employee Records"),
              new XElement("Employees"));

              root = xd.XPathSelectElement("//Employees");

              child = new XElement("Employee",
              new XElement("id", 1),
              new XElement("FirstName", "Bruce"),
              new XElement("LastName", "Jones"));

              root.Add(child);

              xd.Save(AppConfig.XmlFile);

              txtResult.Text = xd.ToString();
        }
        protected DesktopServiceConfiguration(string path, bool useRemoteConfig)
        {
            filePath = path;
            configDoc = XDocument.Load(path);
            XElement configXml = configDoc.XPathSelectElement("//selfServiceDesktops");
            if (configXml == null) {
                throw new ArgumentException("No <selfServiceDesktops/> configuration element found in : " + path);
            }
            config = Deserialize(configXml);

            if (useRemoteConfig && (config.RemoteConfig != null)) {
                try {
                    configXml = GetXml(new Uri(config.RemoteConfig));
                    string remoteConfig = config.RemoteConfig;
                    config = Deserialize(configXml);
                    // If the remote config does not have an agent URI, infer it from the remote Url in the local config
                    if (config.AgentUri == null) {
                        config.SetAgentUriFrom(remoteConfig);
                    }

                } catch (Exception e) {
                    throw new ConfigurationErrorsException("Unable to load configuration from remote server", e);
                }
            }
            ValidateConfiguration();
        }
        static void Main(string[] args)
        {
            var path = @"d:\1";

            var document = new XDocument(
                new XDeclaration("1.0", "UTF-8", null),
                new XElement("root-dir",
                    new XAttribute("path", path)));

            var files = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                var fileDirectories = file.Replace(path, "")
                    .Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                var len = fileDirectories.Length;
                var root = document.Element("root-dir");
                XElement dir = root;

                for (int i = 0; i < len - 1; i++)
                {
                    dir = document.XPathSelectElement(String.Format("//dir[@name = '{0}']", fileDirectories[i]));
                    if (dir == null)
                    {
                        if (i < 1)
                        {
                            dir = root;
                        }
                        else
                        {
                            dir = document.XPathSelectElement(String.Format("//dir[@name = '{0}']", fileDirectories[i - 1]));
                        }

                        var newDir = new XElement("dir",
                            new XAttribute("name", fileDirectories[i]));
                        dir.Add(newDir);
                        dir = newDir;
                    }
                }

                dir.Add(new XElement("file",
                    new XAttribute("name", fileDirectories[len - 1])));
            }

            Console.WriteLine(document.Declaration);
            Console.WriteLine(document);
        }
 private IList<XElement> GetElementsToKeep(XDocument copyDocument, string xpath)
 {
     var elementsToKeep = new List<XElement>();
     var element = copyDocument.XPathSelectElement(xpath, new SimpleXmlNamespaceResolver(copyDocument));
     elementsToKeep.AddRange(element.AncestorsAndSelf());
     elementsToKeep.AddRange(element.Descendants());
     return elementsToKeep;
 }
 private void removeElements (XDocument manifest, params string[] elements) {
     foreach (var element in elements) {
         var e = manifest.XPathSelectElement(element, this);
         if (null != e) {
             e.Remove();
         }
     }
 }
        /// <summary>
        /// Parses the results of a Core Status command.
        /// </summary>
        /// <param name="xml">The XML Document to parse.</param>
        /// <returns></returns>
        public List<CoreResult> Parse(XDocument xml) {
            var statusNode = xml.XPathSelectElement("response/lst[@name='status']");
            if (statusNode == null || !statusNode.HasElements)
                return new List<CoreResult>();

            var results = statusNode.Elements().Select(ParseCore).ToList();
            return results;
        }
Beispiel #16
0
	static void ReplaceRef(XDocument doc, string refName, string id, string path, string name)
	{
		var node = doc.XPathSelectElement($"//p:Reference[@Include='{refName}']", nsManager);
		if (node == null)//means it's already converted to ProjectReference
			return;
		node.Parent.Add(new XElement(ns + "ProjectReference", new XAttribute("Include", path),
			new XElement(ns + "Project", id),
			new XElement(ns + "Name", name)));
		node.Remove();
	}
        public override void ModifyConfig(XDocument doc)
        {
            var sectionElement = doc.XPathSelectElement("/configuration/configSections/section[@name='MasterNodeConfig' and @type='NServiceBus.Config.MasterNodeConfig, NServiceBus.Core']");
            if (sectionElement == null)
            {

                doc.XPathSelectElement("/configuration/configSections").Add(new XElement("section",
                    new XAttribute("name", "MasterNodeConfig"),
                    new XAttribute("type", "NServiceBus.Config.MasterNodeConfig, NServiceBus.Core")));
            }

            var forwardingElement = doc.XPathSelectElement("/configuration/MasterNodeConfig");
            if (forwardingElement == null)
            {
                doc.Root.LastNode.AddAfterSelf(new XComment(Instructions),
                                               new XElement("MasterNodeConfig",
                                                            new XAttribute("Node", "SERVER_NAME_HERE")));
            }
        }
Beispiel #18
0
        public override void ModifyConfig(XDocument doc)
        {
            var sectionElement = doc.XPathSelectElement("/configuration/configSections/section[@name='Logging' and @type='NServiceBus.Config.Logging, NServiceBus.Core']");
            if (sectionElement == null)
            {

                doc.XPathSelectElement("/configuration/configSections").Add(new XElement("section",
                    new XAttribute("name", "Logging"),
                    new XAttribute("type", "NServiceBus.Config.Logging, NServiceBus.Core")));
            }

            var forwardingElement = doc.XPathSelectElement("/configuration/Logging");
            if (forwardingElement == null)
            {
                doc.Root.LastNode.AddAfterSelf(new XComment(Instructions),
                                               new XElement("Logging",
                                                            new XAttribute("Threshold", "INFO")));
            }
        }
Beispiel #19
0
    public static void Save(Post post, string file)
    {
        post.LastModified = DateTime.UtcNow;

        XDocument doc = new XDocument(
                        new XElement("post",
                            new XElement("title", post.Title),
                            new XElement("slug", post.Slug),
                            new XElement("author", post.Author),
                            new XElement("pubDate", post.PubDate.ToString("yyyy-MM-dd HH:mm:ss")),
                            new XElement("lastModified", post.LastModified.ToString("yyyy-MM-dd HH:mm:ss")),
                            new XElement("content", post.Content),
                            new XElement("ispublished", post.IsPublished),
                            new XElement("categories", string.Empty),
                            new XElement("comments", string.Empty)
                        ));

        XElement categories = doc.XPathSelectElement("post/categories");
        foreach (string category in post.Categories)
        {
            categories.Add(new XElement("category", category));
        }

        XElement comments = doc.XPathSelectElement("post/comments");
        foreach (Comment comment in post.Comments)
        {
            comments.Add(
                new XElement("comment",
                    new XElement("author", comment.Author),
                    new XElement("email", comment.Email),
                    new XElement("website", comment.Website),
                    new XElement("ip", comment.Ip),
                    new XElement("userAgent", comment.UserAgent),
                    new XElement("date", comment.PubDate.ToString("yyyy-MM-dd HH:m:ss")),
                    new XElement("content", comment.Content),
                    new XAttribute("isAdmin", comment.IsAdmin),
                    new XAttribute("id", comment.ID)
                ));
        }

        doc.Save(file);
    }
Beispiel #20
0
 static void CreateConfigSectionIfRequired(XDocument doc)
 {
     if (doc.Root == null)
     {
         doc.Add(new XElement("/configuration"));
     }
     if (doc.XPathSelectElement("/configuration/configSections") == null)
     {
         doc.Root.AddFirst(new XElement("configSections"));
     }
 }
        public ExtractResponse Parse(XDocument response)
        {
            var responseHeader = headerResponseParser.Parse(response);

            var contentNode = response.XPathSelectElement("response/str");
            var extractResponse = new ExtractResponse(responseHeader) {
                Content = contentNode != null ? contentNode.Value : null
            };

            return extractResponse;
        }
Beispiel #22
0
 // ────────────────────────── Constructor ──────────────────────────
 public Configuration(XDocument configuration)
 {
     try
     {
         XNode servicesNode = configuration.XPathSelectElement("configuration/system.serviceModel");
         Source = XDocument.Load(servicesNode.CreateReader());
     }
     catch (Exception exception)
     {
         throw new Exception(string.Format("Unable to open service model configuration section in file: {0}", exception.Message));
     }
 }
        public override void ModifyConfig(XDocument doc)
        {
            var sectionElement = doc.XPathSelectElement("/configuration/configSections/section[@name='SecondLevelRetriesConfig' and @type='NServiceBus.Config.SecondLevelRetriesConfig, NServiceBus.Core']");
            if (sectionElement == null)
            {

                doc.XPathSelectElement("/configuration/configSections").Add(new XElement("section",
                    new XAttribute("name", "SecondLevelRetriesConfig"),
                    new XAttribute("type", "NServiceBus.Config.SecondLevelRetriesConfig, NServiceBus.Core")));
            }

            var forwardingElement = doc.XPathSelectElement("/configuration/SecondLevelRetriesConfig");
            if (forwardingElement == null)
            {
                doc.Root.LastNode.AddAfterSelf(new XComment(Instructions),
                                               new XElement("SecondLevelRetriesConfig",
                                                            new XAttribute("Enabled", "true"),
                                                            new XAttribute("NumberOfRetries", "3"),
                                                            new XAttribute("TimeIncrease", "00:00:10")));
            }
        }
        public override void ModifyConfig(XDocument doc)
        {
            var sectionElement = doc.XPathSelectElement("/configuration/configSections/section[@name='TransportConfig' and @type='NServiceBus.Config.TransportConfig, NServiceBus.Core']");
            if (sectionElement == null)
            {

                doc.XPathSelectElement("/configuration/configSections").Add(new XElement("section",
                    new XAttribute("name", "TransportConfig"),
                    new XAttribute("type", "NServiceBus.Config.TransportConfig, NServiceBus.Core")));
            }

            var forwardingElement = doc.XPathSelectElement("/configuration/TransportConfig");
            if (forwardingElement == null)
            {
                doc.Root.LastNode.AddAfterSelf(new XComment(Instructions),
                                               new XElement("TransportConfig",
                                                            new XAttribute("MaxRetries", "5"),
                                                            new XAttribute("MaximumConcurrencyLevel", "1"),
                                                            new XAttribute("MaximumMessageThroughputPerSecond", "0")));
            }
        }
        public string GetProjectAssemblyName(string platform, DefinitionInfo definition, XDocument document)
        {
            var assemblyNameForPlatformElement = document.XPathSelectElement("/Project/Properties/AssemblyName/Platform[@Name=\"" + platform + "\"]");
            var assemblyNameGlobalElement = document.XPathSelectElement("/Project/Properties/Property[@Name=\"AssemblyName\"]");

            string assemblyName = null;
            if (assemblyNameForPlatformElement != null)
            {
                assemblyName = assemblyNameForPlatformElement.Value;
            }
            else if (assemblyNameGlobalElement != null)
            {
                assemblyName = assemblyNameGlobalElement.Attribute(XName.Get("Value")).Value;
            }
            else
            {
                assemblyName = definition.Name;
            }

            return assemblyName;
        }
        static void Main(string[] args)
        {
            string catalog = System.IO.File.ReadAllText("catalog.xml");

            System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Parse(catalog);

            var targetBook       = xdoc.XPathSelectElement("//catalog/book[@id='bk101']");
            var targetBookTitle  = targetBook.XPathSelectElement("title").Value;
            var targetBookAuthor = targetBook.XPathSelectElement("author").Value;

            Console.Write($"{ targetBookTitle} - { targetBookAuthor}");
            Console.Read();
        }
        public override void ModifyConfig(XDocument doc)
        {
            var sectionElement = doc.XPathSelectElement("/configuration/configSections/section[@name='UnicastBusConfig' and @type='NServiceBus.Config.UnicastBusConfig, NServiceBus.Core']");
            if (sectionElement == null)
            {

                doc.XPathSelectElement("/configuration/configSections").Add(new XElement("section",
                                                                                         new XAttribute("name",
                                                                                                        "UnicastBusConfig"),
                                                                                         new XAttribute("type",
                                                                                                        "NServiceBus.Config.UnicastBusConfig, NServiceBus.Core")));

            }

            var forwardingElement = doc.XPathSelectElement("/configuration/UnicastBusConfig");
            if (forwardingElement == null)
            {
                doc.Root.LastNode.AddAfterSelf(
                                                new XComment(Instructions), 
                                                new XElement("UnicastBusConfig",
                                                new XElement("MessageEndpointMappings")));
            }
        }
Beispiel #28
0
        private static void AddMissingCrmAttribute(XDocument xDoc, string attributeName)
        {
            var xBuAttribute = xDoc.XPathSelectElement("fetch/entity/attribute[@name='" + attributeName + "']");
            if (xBuAttribute == null)
            {
                var entityElement = xDoc.Descendants("entity").FirstOrDefault();
                if (entityElement == null)
                {
                    throw new Exception("Cannot find node 'entity' in FetchXml");
                }

                entityElement.Add(new XElement("attribute", new XAttribute("name", attributeName)));
            }
        }
Beispiel #29
0
        private string ReadXPathElementValue(XDocument doc, string xpath)
        {
            var value = string.Empty;

            var mgr = new XmlNamespaceManager(new NameTable());
            mgr.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");

            var element = doc.XPathSelectElement(xpath.Replace("/", "/x:"), mgr);
            if (element != null)
            {
                value = element.Value;
            }

            return value;
        }
        public string Transform(XDocument document)
        {
            // <div class="maintext">
            var element = document.XPathSelectElement("//*[@class='maintext']");

            if (element == null) return string.Empty;

            element = Transform(element);

            var result = new XDocument(
                new XElement("section",
                    element.Elements()
                )
            );

            return result.ToString();
        }
        public NewArmyForm(String pn, HexCoords c, object[] sizeArr)
        {
            InitializeComponent();

            playerName = pn;
            coords = c;

            playerDoc = XDocument.Load(Player.SavePath);
            String race = playerDoc.XPathSelectElement("Players/Player[Name=\"" + playerName + "\"]/Race").Value;
            raceDoc = XDocument.Load(Race.GetConfigDoc(race));

            foreach (var e in raceDoc.XPathSelectElements("Config/ArmyTypes/ArmyType"))
            {
                lbArmyTypes.Items.Add(e.Attribute("Type").Value);
            }

            cbSize.Items.AddRange(sizeArr);
        }
Beispiel #32
0
        /// <summary>
        /// This method will parse html and try to serach the url in the html
        /// Not the best way to to parse html may be we should use the htmlagility pack
        /// </summary>
        /// <param name="sanitizedHtml"></param>
        /// <param name="urlToBeSearched"></param>
        /// <returns></returns>
        public virtual string ParseAndSearch(string sanitizedHtml, string urlToBeSearched)
        {
            IEnumerable <XElement> nextChildDivs = null;
            XElement      resultElement          = null;
            bool          matchFound             = false;
            int           counter    = 1;
            StringBuilder rankString = new StringBuilder();

            System.Xml.Linq.XDocument xd = System.Xml.Linq.XDocument.Parse(sanitizedHtml);

            resultElement = xd.XPathSelectElement("descendant::div[@id='ires']");
            nextChildDivs = xd.XPathSelectElements("descendant::div[@class='g']");

            if (nextChildDivs != null)
            {
                foreach (XElement childNode in nextChildDivs)
                {
                    var siteUrlNode = childNode.Descendants("cite").FirstOrDefault();

                    if (siteUrlNode != null && siteUrlNode.Value.Contains(urlToBeSearched))
                    {
                        if (matchFound)
                        {
                            rankString.Append(",");
                        }
                        rankString.Append(counter);
                        matchFound = true;
                    }
                    if (siteUrlNode != null)
                    {
                        counter++;
                    }
                }
            }
            if (!matchFound)
            {
                return(NoMatchFound);
            }
            else
            {
                return(rankString.ToString());
            }
        }
Beispiel #33
0
 /// <summary>
 /// 获取xPath匹配到的第一个元素
 /// </summary>
 /// <param name="xPath">xPath表达式</param>
 /// <returns>匹配到的XElement对象</returns>
 public XElement GetXElement(string xPath)
 {
     return(_doc.XPathSelectElement(xPath));
 }