C #을 사용하여 구문 분석하는 일부 HTML이 있습니다.
샘플 텍스트는 아래에 있지만 다른 레코드로 약 150 번 반복됩니다.
<strong>Title</strong>: Mr<br>
<strong>First name</strong>: Fake<br>
<strong>Surname</strong>: Guy<br>
나는 배열과 같은 텍스트를 얻으려고합니다.
customerArray [0,0] = Title
customerArray [0,1] = Mr
customerArray [1,0] = First Name
customerArray [1,1] = Fake
customerArray [2,0] = Surname
customerArray [2,1] = Guy
배열에서 텍스트를 가져올 수 있지만 STR 태그를 닫은 후 BR 태그까지 텍스트를 가져 와서 다음 STRONG 태그를 찾는 데 문제가 있습니다.
어떤 도움을 주시면 감사하겠습니다.
XPath의 following-sibling::text()[1]
을 사용하여 각 strong
뒤에 텍스트 노드를 직접 가져올 수 있습니다. 다음은 최소한이지만 완전한 예입니다.
var raw = @"<div>
<strong>Title</strong>: Mr<br>
<strong>First name</strong>: Fake<br>
<strong>Surname</strong>: Guy<br>
</div>";
var doc = new HtmlDocument();
doc.LoadHtml(raw);
foreach(HtmlNode node in doc.DocumentNode.SelectNodes("//strong"))
{
var val = node.SelectSingleNode("following-sibling::text()[1]");
Console.WriteLine(node.InnerText + ", " + val.InnerText);
}
출력 :
Title, : Mr
First name, : Fake
Surname, : Guy
필요한 경우 간단한 문자열 조작을 수행하여 ":"를 제거 할 수 있어야합니다.
<strong>
는 일반적인 태그이므로 제공 한 샘플 형식에 특정한 내용입니다.
var html = @"
<div>
<strong>First name</strong><em>italic</em>: Fake<br>
<strong>Bold</strong> <a href='#'>hyperlink</a><br>.
<strong>bold</strong>
<strong>bold</strong> <br>
text
</div>
<div>
<strong>Title</strong>: Mr<BR>
<strong>First name</strong>: Fake<br>
<strong>Surname</strong>: Guy<br>
</div>";
var document = new HtmlDocument();
document.LoadHtml(html);
// 1. <strong>
var strong = document.DocumentNode.SelectNodes("//strong");
if (strong != null)
{
foreach (var node in strong.Where(
// 2. followed by non-empty text node
x => x.NextSibling is HtmlTextNode
&& !string.IsNullOrEmpty(x.NextSibling.InnerText.Trim())
// 3. followed by <br>
&& x.NextSibling.NextSibling is HtmlNode
&& x.NextSibling.NextSibling.Name.ToLower() == "br"))
{
Console.WriteLine("{0} {1}", node.InnerText, node.NextSibling.InnerText);
}
}