【发布时间】:2016-05-31 05:38:48
【问题描述】:
我有一个 c# 代码,它将读取一个 html 文件并将其内容作为字符串/文本返回。
我需要做的一件事是解析html字符串,查找所有<embed>标签,获取“src”属性中的值,然后用找到的文件内容替换整个<embed>标签在src 标签中。
我正在尝试使用 HtmlAgilityPack 来解析 html 代码。
我唯一不能做的就是如何将<embed>标签替换为另一个字符串,最后将没有<embed>标签的新字符串返回给用户。
这是我所做的
protected string ParseContent(string content)
{
if (content != null)
{
//Create a new document parser object
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
//load the content
document.LoadHtml(content);
//Get all embed tags
IEnumerable<HtmlNode> embedNodes = document.DocumentNode.Descendants("embed");
//Make sure the content contains at least one <embed> tag
if (embedNodes.Count() > 0)
{
// Outputs the href for external links
foreach (HtmlNode embedNode in embedNodes)
{
//Mak sure there is a source
if (embedNode.Attributes.Contains("src"))
{
//If the file ends with ".html"
if (embedNode.Attributes["src"].Value.EndsWith(".html"))
{
var newContent = GetContent(embedNode.Attributes["src"].Value);
//Here I need to be able to replace the entireembedNode with the newContent
}
}
}
}
return content;
}
return null;
}
protected string GetContent(string path)
{
if (System.IO.File.Exists(path))
{
//The file exists, read its content
return System.IO.File.ReadAllText(path);
}
return null;
}
如何将<embed> 标记替换为字符串?
【问题讨论】:
标签: c# asp.net asp.net-mvc-4 asp.net-mvc-5 html-agility-pack