특정 텍스트 문자열을 포함하는 모든 html 요소 (태그)를 제거하려고합니다. 나는 2376 개의 HTML 문서를 가지고 있으며, 모두 다른 doctype 표준을 사용한다. 일부는 doctype이 없습니다 (이 질문과 관련이 없을 수 있음).
그래서 "이 논문을 인용하는 방법"이라는 텍스트 문자열을 찾고 있는데, <p>-tag
, <h4>-tag
또는 <legend>-tag
내에 포함되어있는 것으로 나타났습니다.
<p>-tag
종종 다음과 같이 보입니다.
<p style="text-align : center; color : Red; font-weight : bold;">How to cite this paper:</i></p>
<h4>-tag
종종 이렇게 보입니다.
<h4>How to cite this paper:</h4>Antunes, P., Costa, C.J. & Pino, J.A. (2006).
<legend>-tag
는 다음과 같습니다.
<legend style="color: white; background-color: maroon; font-size: medium; padding: .1ex .5ex; border-right: 1px solid navy; border-bottom: 1px solid navy; font-weight: bold;">How to cite this paper</legend>
현재 진행중인 작업은 이러한 태그를 찾아서 파일에서 제거한 다음 파일을 다시 저장하는 것입니다. 제거 할 태그가 더 많지만 HAP 및 XPath를 이해하는 데 도움이되고 값이나 다른 고유 한 데이터를 기반으로 특정 태그를 찾는 방법이 필요합니다.
지금까지 C #으로이 코드를 만들었습니다.이 코드는 콘솔 응용 프로그램입니다. 이것은 나의 메인 (나쁜 들여 쓰기에 대해 유감스럽게 생각한다)이다.
//Variables
string Ext = "*.html";
string folder = @"D:\websites\dev.openjournal.tld\public\arkivet\";
IEnumerable<string> files = GetHTMLFiles(folder, Ext);
List<string> cite_files = new List<string>();
var doc = new HtmlDocument();
//Loop to match all html-elements to query
foreach (var file in files)
{
try
{
doc.Load(file);
cite_files.Add(doc.DocumentNode.SelectNodes("//h4[contains(., 'How to cite this paper')]").ToString());
cite_files.Add(doc.DocumentNode.SelectNodes("//p[contains(., 'How to cite this paper')]").ToString());
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
}
}
//Counts numbers of hits and prints data to user
int filecount = files.Count();
int citations = cite_files.Count();
Console.WriteLine("Number of files scanned: " + filecount);
Console.WriteLine("Number of citations: {0}", citations);
// Program end
Console.WriteLine("Press any key to close program....");
Console.ReadKey();
그리고 이것은 디렉토리를 통해 파일을 찾는 개인적인 방법입니다.
//List all HTML-files recursively and return them to a list
public static IEnumerable<string> GetHTMLFiles(string directory, string Ext)
{
List<string> files = new List<string>();
try
{
files.AddRange(Directory.GetFiles(directory, Ext, SearchOption.AllDirectories));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return files;
}
이 독특한 단어를 포함하는 모든 특정 태그를 찾은 다음 제거하려고하는 독특한 방법은 "이 종이를 인용하는 방법"인 것 같습니다. 메모장에이 문구가 포함 된 1094 개의 파일이 있어야하므로 모든 파일을 가져 오려고합니다. :)
어떤 도움을 주셔서 감사합니다! :)
Html Agility Pack은 LINQ 선택기를 지원하며,이 경우 매우 편리합니다. 위의 예를 기반으로 HTML을 살펴보십시오.
var html =
@"<html><head></head><body>
<!-- selector match: delete these nodes -->
<p style='text-align: center; color: Red; font-weight: bold;'>How to cite this paper:</i></p>
<h4> How to cite this paper:</h4> Antunes, P., Costa, C.J. & amp; Pino, J.A. (2006).
<legend style='color: white; background-color: maroon; font-size: medium; padding: .1ex .5ex; border-right: 1px solid navy; border-bottom: 1px solid navy; font-weight: bold;'>How to cite this paper </legend>
<div><p><i><b>How to cite this paper (NESTED)</b></i></p></div>
<!-- no match: keep these nodes -->
<p>DO NOT DELETE - How to cite</p>
<h4>DO NOT DELETE - cite this paper:</h4>
<legend>DO NOT DELETE</legend>
</body></html>";
검색해야 할 태그 모음을 만들고 일치하는 노드를 선택한 다음 다음과 같이 제거 할 수 있습니다.
var tagsToDelete = new string[] { "p", "h4", "legend" };
var nodesToDelete = new List<HtmlNode>();
var document = new HtmlDocument();
document.LoadHtml(html);
foreach (var tag in tagsToDelete)
{
nodesToDelete.AddRange(
from searchText in document.DocumentNode.Descendants(tag)
where searchText.InnerText.Contains("How to cite this paper")
select searchText
);
}
foreach (var node in nodesToDelete) node.Remove();
document.Save(OUTPUT);
다음 결과로 :
<html><head></head><body>
<!-- XPath match: delete these nodes -->
Antunes, P., Costa, C.J. & amp; Pino, J.A. (2006).
<div></div>
<!-- no match, keep these nodes -->
<p>DO NOT DELETE - How to cite</p>
<h4>DO NOT DELETE - cite this paper:</h4>
<legend>DO NOT DELETE</legend>
</body></html>