c# - 如何编辑所有特殊 html 标签的属性(如 a)

标签 c# asp.net html c#-4.0

我正在尝试使用 C# 编辑所有特殊 html 标签(如 a)的属性。例如我想更改此代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
</head>
<body>
    <a href="http://google.com"></a>
    <a href="http://gmail.com"></a>
</body>
</html>

为此:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
</head>
<body>
    <a href="http://go.go/default.aspx?url=http://google.com">
    </a><a href="http://go.go/default.aspx?url=http://gmail.com"></a>
</body>
</html>

这意味着我想追加href的值在<a>

我试过 LinqToXML 但没有成功,因为 HTML 不是有效的 XML(因为 DOCTYPE 标签)

这是我的代码:

XDocument xmlFile = XDocument.Load(s);

var query = from c in xmlFile.Elements("html").Elements("body").Elements("a")
            select c;

foreach (XElement book in query)
{
    string atr = book.Attribute("href").Value;
    book.Attribute("href").Value = "http://ahmadalli.somee.com/default.aspx?url=" + atr;
}

xmlFile.Save(s);

s是我的 html 流。

有谁知道我该怎么做?

我想在 ASP.NET 中使用这段代码

最佳答案

看看 HTML Agility Pack .

What is exactly the Html Agility Pack (HAP)?

This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).

下载包含几个示例项目 - 检查它们以了解如何操作 HTML 文件。

关于c# - 如何编辑所有特殊 html 标签的属性(如 a),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9134761/

相关文章:

c# - AccessType = Offline 在 C# 中的 Google Analytics OAuth

c# - 启动 ASP.NET MVC 4 应用程序时执行代码

Asp.Net(C#) Jquery Ajax 与 WebMethod 调用问题

html - Bootstrap 下 zipper 接在移动设备上被切断

javascript - 从输入类型 ="date"到新日期的日期是不正确的日期输出

javascript - CSS - 将右侧边距与自动换行的工具提示段落对齐

c# - 比特币哈希算法

c# - 在 C# 中优化 Linq

c# - 如何解决未将对象引用设置为对象实例的问题。?

c# - 将具有随机行和列(由对象定义)的表导出到 Excel