私はHtmlAgilityPackライブラリを使用する他のWebサイトの文字列と一致させるために正規表現を使用するコードを変換する方法を知りたいと思います。
コード例:
<div class="element"><div class="title"><a href="127.0.0.1" title="A.1">A.1</a></div></div>
<div class="element"><div class="title"><a href="127.0.0.1" title="A.2">A.2</a></div></div>
私の現在のコードは次のとおりです:
List<string> Cap = new List<string>();
WebClient web = new WebClient();
string url = web.DownloadString("127.0.0.1");
MatchCollection cap = Regex.Matches(url, "title=\"(.+?)\">", RegexOptions.Singleline);
foreach (Match m in cap)
{
Cap.Add(m.Groups[1].Value.ToString());
}
lst_Cap.ItemsSource = Cap;
そして、それは動作します。
私はHtmlAgilityPackで試しました:
HtmlDocument Web = web.Load("127.0.0.1"); // 127.0.0.1 for example
List<string> Cap = new List<string>();
foreach (HtmlNode node in Web.DocumentNode.SelectNodes("//*[@id=\"content\"]/div/div[3]/div[2]/div[1]/a"))
{
Cap.Add(node.InnerHtml);
}
しかし、それはA.1だけを追加します。
どのようにできるのか?
あなたのregex "title=\"(.+?)\">"
は、HTMLドキュメント内の任意のタグ内の任意のtitle属性にマッチしキャプチャします。
したがって、 title属性を含む任意の要素ノード( *
)を取得し、属性ノードを反復し、その名前がtitle
たら、その値をリストに追加する//*[@title]
XPathで別のコードを使用します。
var nodes = Web.DocumentNode.SelectNodes("//*[@title]");
if (nodes != null)
{
foreach (var node in nodes)
{
foreach (var attribute in node.Attributes)
if (attribute.Name == "title")
Cap.Add(attribute.Value);
}
}
またはLINQを使用する:
var nodes = Web.DocumentNode.SelectNodes("//*[@title]");
var res = nodes.Where(p => p.HasAttributes)
.Select(m => m.GetAttributeValue("title", string.Empty))
.Where(l => !string.IsNullOrEmpty(l))
.ToList();