2012-11-01 78 views
-5

一個字符串我有以下字符串"</script><div id='PO_1WTXxKUTU98xDU1'><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>"搜索使用C#

我需要擺脫div標籤的屬性值。我如何檢索這個使用C#。

+6

所以......那你試試? – LukeHennerley

+1

http://stackoverflow.com/questions/56107/what-is-the-best-way-to-parse-html-in-c ...和in-particular:http://stackoverflow.com/a/ 6244203/608764 – AlexFZ

回答

0

如果你是一個受虐狂,你可以做到這一點老派風格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

避免解析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 
+4

誰對正則表達式有任何評論? –

+1

@JonB他用正則表達式標記 – Anirudha

+0

所以你認爲你很聰明只是因爲你知道如何閱讀? Pfft! –

-1

一個.NET正則表達式,看起來像這將這樣的伎倆

^</script><div id='(?<attrValue>[^']+)'.*$ 

那麼你就可以得到價值保持爲

MatchCollection matches = Regex.Matches(input, @"^</script><div id='(?<attrValue>[^']+)'.*$"); 
if (matches.Count > 0) 
{ 
    var attrValue = matches[0].Groups["attrValue"]; 
} 
0

嚴格要求解決,一個問題解決這個問題的無數方法是隔離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; 

確實有很多方法可以解決這個問題,但是這個回答郵件。

+0

我想用linq2xml是一個很好的方法來解決這個問題。特別是如果它的html – Anirudha

+0

那麼,你肯定允許你的意見。它*確實*回答了這個問題,並且不需要依賴另一個庫來完成它。 – itsmatt