gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:22:07 25 4
gpt4 key购买 nike

我正在尝试使用 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/

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