ASP.NET MVC 3 Parse simple html tag/extract attribute value
What is the best way to parse html tag like that:
<a href="/Results">Results</a>
i just need to extract a href value.
I need to do this on controller.
I know i may use linq to xml
for example or regex
.
Any ideas what is the better way for that case?
May be there is any MVC helpers ready to go?
Basically what i need to do:
I have my extension method witch returning current url
public static string GetCurrentUrl(this ViewContext context)
{
string action = (string)context.Controller.ValueProvider.GetValue("action").RawValue;
string controller = (string)context.Controller.ValueProvider.GetValue("controller").RawValue;
if (action.ToLower() != "index开发者_如何学Python")
return String.Format("/{0}/{1}", controller, action);
else if (action.ToLower() != "index" && controller.ToLower() != "home")
return String.Format("/{0}", controller);
else
return "/";
}
I need to compare this url with the value from a href like that <a href="{here cold be any link}">Results</a>
Use a XML parser and avoid regex. For this specific case XDocument seems easy enough:
var doc = XDocument.Parse("<a href=\"/Results\">Results</a>");
var href = doc.Element("a").Attribute("href").Value;
For more complex scenarios when HTML specific parsing is required and manipulating the DOM you could use HTML Agility Pack.
parsing html is notoriously difficult, there are so many hidden gotchas. The HTML Agility pack, which is a .NET HTML parsing library. Fizzler enables css selectors for html in c# and is built on top of the agility pack.
精彩评论