Mam*_*iga 2 c# tags string href
我有一个C#函数,它返回一个字符串,格式如下:
string tableTag = "<th><a href="Boot_53.html">135 Boot</a></th>"
Run Code Online (Sandbox Code Playgroud)
我想获得href链接并存储到另一个名为link的字符串中:
string link = "Boot_53.html"
Run Code Online (Sandbox Code Playgroud)
我怎么能在C#中做到这一点?
您可以使用HTML解析器,例如HTML agility pack解析输入的HTML并提取您要查找的信息:
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var doc = new HtmlDocument();
string tableTag = "<th><a href=\"Boot_53.html\">135 Boot</a></th>";
doc.LoadHtml(tableTag);
var anchor = doc.DocumentNode.SelectSingleNode("//a");
if (anchor != null)
{
string link = anchor.Attributes["href"].Value;
Console.WriteLine(link);
}
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用正则表达式:
string input= "<th><a href=\"Boot_53.html\">135 Boot</a></th>";
string regex= "href=\"(.*)\"";
Match match = Regex.Match(input, regex);
if (match.Success)
{
string link= match.Groups[1].Value;
Console.WriteLine(link);
}
Run Code Online (Sandbox Code Playgroud)
如果您知道html实际上是一个xhtml(一个符合xml标准[或多或少]的html),您只需使用专用于xml的工具(通常比html更简单)解析.
var hrefLink = XElement.Parse("<th><a href=\"Boot_53.html\">135 Boot</a></th>")
.Descendants("a")
.Select(x => x.Attribute("href").Value)
.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)