J’ai une fonction C # qui renvoie une chaîne au format suivant:
ssortingng tableTag = "135 Boot "
Je veux obtenir le lien href et le stocker dans une autre chaîne appelée link:
ssortingng link = "https://stackoverflow.com/questions/22151037/how-to-extract-href-tag-from-a-string-in-c/Boot_53.html"
Comment puis-je faire cela en C #?
Si vous savez que le code HTML est en fait un xhtml (un code conforme aux standards xml [plus ou moins]), vous pouvez parsingr simplement avec des outils dédiés au xml (qui sont généralement plus simples que ceux du code HTML).
var hrefLink = XElement.Parse("135 Boot ") .Descendants("a") .Select(x => x.Atsortingbute("href").Value) .FirstOrDefault();
Vous pouvez utiliser Regex:
ssortingng input= "135 Boot "; ssortingng regex= "href=\"(.*)\""; Match match = Regex.Match(input, regex); if (match.Success) { ssortingng link= match.Groups[1].Value; Console.WriteLine(link); }
Vous pouvez utiliser un parsingur HTML tel que HTML agility pack
pour parsingr le code HTML d’entrée et extraire les informations que vous recherchez:
using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main(ssortingng[] args) { var doc = new HtmlDocument(); ssortingng tableTag = "135 Boot "; doc.LoadHtml(tableTag); var anchor = doc.DocumentNode.SelectSingleNode("//a"); if (anchor != null) { ssortingng link = anchor.Atsortingbutes["href"].Value; Console.WriteLine(link); } } }
Utilisez HtmlAgilityPack
pour parsingr HTML:
var doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml( tableTag ); ssortingng link = doc.DocumentNode.SelectSingleNode("//a").Atsortingbutes["href"].Value;