一個字符串我有以下字符串"</script><div id='PO_1WTXxKUTU98xDU1'><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>"
搜索使用C#
我需要擺脫div標籤的屬性值。我如何檢索這個使用C#。
一個字符串我有以下字符串"</script><div id='PO_1WTXxKUTU98xDU1'><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>"
搜索使用C#
我需要擺脫div標籤的屬性值。我如何檢索這個使用C#。
如果你是一個受虐狂,你可以做到這一點老派風格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);
}
避免解析HTML與regex
Regex
不是解析HTML
文件一個不錯的選擇..
HTML不嚴格,也不是經常用它的格式..
你可以用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
一個.NET正則表達式,看起來像這將這樣的伎倆
^</script><div id='(?<attrValue>[^']+)'.*$
那麼你就可以得到價值保持爲
MatchCollection matches = Regex.Matches(input, @"^</script><div id='(?<attrValue>[^']+)'.*$");
if (matches.Count > 0)
{
var attrValue = matches[0].Groups["attrValue"];
}
嚴格要求解決,一個問題解決這個問題的無數方法是隔離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;
確實有很多方法可以解決這個問題,但是這個回答郵件。
所以......那你試試? – LukeHennerley
http://stackoverflow.com/questions/56107/what-is-the-best-way-to-parse-html-in-c ...和in-particular:http://stackoverflow.com/a/ 6244203/608764 – AlexFZ