私は次の文字列を持っています"</script><div id='PO_1WTXxKUTU98xDU1'><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>"
div タグから属性値を取得する必要があります。C# を使用してこれを取得するにはどうすればよいですか。
でhtmlを解析しないでくださいregex
Regex
HTML
ファイルの解析には適していません。
HTML は厳密ではなく、その形式も規則的ではありません。
htmlagilityPackを使用する
htmlagilityPack を使用すると、このようにすることができます。
HtmlDocument doc = new HtmlDocument();
doc.Load(yourStream);
List<string> itemList = doc.DocumentNode.SelectNodes("//div[@id]")//selects all div having id attribute
.Select(x=>x.Attributes["id"].Value)//select the id attribute value
.ToList<string>();
//itemList will now contain all div's id attribute value
あなたがマゾヒストなら、この古い学校の VB3 スタイルを実行できます。
string input = @"</script><div id='PO_1WTXxKUTU98xDU1'><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>";
string startString = "div id='";
int startIndex = input.IndexOf(startString);
if (startIndex != -1)
{
startIndex += startString.Length;
int endIndex = input.IndexOf("'", startIndex);
string subString = input.Substring(startIndex, endIndex - startIndex);
}
尋ねられた質問を厳密に解決します。それを解決する無数の方法の 1 つは、div
要素を分離し、それを として解析し、XElement
その方法で属性の値を取得することです。
string bobo = "</script><div id='PO_1WTXxKUTU98xDU1'><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>";
string justDiv = bobo.Substring(bobo.IndexOf("<div"));
XElement xelem = XElement.Parse(justDiv);
var id = xelem.Attribute("id");
var value = id.Value;
これを解決する方法は確かにたくさんありますが、これはメールに答えるものです。