我有下面的格式返回字符串的C#功能:如何從C#中的字符串中提取href標記?
string tableTag = "<th><a href="Boot_53.html">135 Boot</a></th>"
我想要得到的HREF鏈接,並存儲到另一個字符串稱爲鏈接:
string link = "Boot_53.html"
我怎麼能這樣做在C#中?
我有下面的格式返回字符串的C#功能:如何從C#中的字符串中提取href標記?
string tableTag = "<th><a href="Boot_53.html">135 Boot</a></th>"
我想要得到的HREF鏈接,並存儲到另一個字符串稱爲鏈接:
string link = "Boot_53.html"
我怎麼能這樣做在C#中?
如果您知道html實際上是一個xhtml(an符合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();
使用HtmlAgilityPack
解析HTML:
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(tableTag);
string link = doc.DocumentNode.SelectSingleNode("//a").Attributes["href"].Value;
你可以使用一個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);
}
}
}
您可以使用正則表達式:
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);
}
'我該怎麼做C#?'不是一個好問題。顯示你到目前爲止所嘗試的,你卡在哪裏.. –
看看這個SO回答http://stackoverflow.com/a/15926523/1593273 –