나는 수천 (ASP.net - 지저분한 HTML) html 생성 된 인보이스를 구문 분석하고 데이터베이스에 저장하려고합니다.
기본적으로 다음과 같습니다.
foreach(var htmlDoc in HtmlFolder)
{
foreach(var inputBox in htmlDoc)
{
//Make Collection of ID and Values Insert to DB
}
}
이 유형의 문제에 가장 적합한 도구를 읽은 다른 모든 질문 은 HtmlAgilityPack입니다 .하지만 나에게있어서 .chm 파일은 작동하지 않습니다. Agility Pack의 유무에 관계없이이를 수행 할 수있는 방법에 대한 아이디어가 있습니까?
미리 감사드립니다.
HtmlAgilityPack에 대한 새로운 대안은 CsQuery 입니다. 상대적인 성능상의 장점에 대해서는 나중에이 질문을 참조하십시오. 그러나 CSS 선택기를 사용하면 이길 수 없습니다.
var doc = CQ.CreateDocumentFromFile(htmldoc); //load, parse the file
var fields = doc["input"]; //get input fields with CSS
var pairs = fields.Select(node => new Tuple<string, string>(node.Id, node.Value()))
//get values
CHM을 사용하려면 Windows 탐색기에서 속성을보고 "내용 차단 해제"확인란의 선택을 취소해야 합니다.
Linq-to-XML 또는 XPath를 사용하는 방법을 알면 HTML Agility Pack을 매우 쉽게 사용할 수 있습니다.
알아야 할 기본 사항은 다음과 같습니다.
//import the HtmlAgilityPack
using HtmlAgilityPack;
HtmlDocument doc = new HtmlDocument();
// Load your data
// -----------------------------
// Load doc from file:
doc.Load(pathToFile);
// OR
// Load doc from string:
doc.LoadHtml(contentsOfFile);
// -----------------------------
// Find what you're after
// -----------------------------
// Finding things using Linq
var nodes = doc.DocumentNode.DescendantsAndSelf("input")
.Where(node => !string.IsNullOrWhitespace(node.Id)
&& node.Attributes["value"] != null
&& !string.IsNullOrWhitespace(node.Attributes["value"].Value));
// OR
// Finding things using XPath
var nodes = doc.DocumentNode
.SelectNodes("//input[not(@id='') and not(@value='')]");
// -----------------------------
// looping through the nodes:
// the XPath interfaces can return null when no nodes are found
if (nodes != null)
{
foreach (var node in nodes)
{
var id = node.Id;
var value = node.Attributes["value"].Value;
}
}
HtmlAgility Pack 을 추가하는 가장 쉬운 방법 은 NuGet을 사용하는 것입니다 .
PM> 설치 패키지 HtmlAgilityPack