gpt4 book ai didi

asp.net-mvc-3 - ASP.NET MVC 3 解析简单的 html 标记/提取属性值

转载 作者:行者123 更新时间:2023-12-01 01:28:56 25 4
gpt4 key购买 nike

像这样解析 html 标签的最佳方法是什么:

<a href="/Results">Results</a>

我只需要提取一个 href 值。

我需要在 Controller 上执行此操作。

我知道我可以使用 linq to xml例如或 regex .

任何想法什么是这种情况下更好的方法?

可能有任何 MVC 助手准备好了?

基本上我需要做的是:

我有我的扩展方法女巫返回当前网址
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")
return String.Format("/{0}/{1}", controller, action);
else if (action.ToLower() != "index" && controller.ToLower() != "home")
return String.Format("/{0}", controller);
else
return "/";
}

我需要将这个 url 与来自这样的 href 的值进行比较 <a href="{here cold be any link}">Results</a>

最佳答案

使用 XML 解析器并避免使用正则表达式。对于这个特定案例 XDocument似乎很容易:

var doc = XDocument.Parse("<a href=\"/Results\">Results</a>");
var href = doc.Element("a").Attribute("href").Value;

对于需要特定于 HTML 的解析和操作 DOM 的更复杂的场景,您可以使用 HTML Agility Pack .

关于asp.net-mvc-3 - ASP.NET MVC 3 解析简单的 html 标记/提取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6002984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com