2011-04-11 95 views
0

我使用C#並需要解析HTML以將屬性讀取到鍵值對中。 例如給出下面的HTML代碼段
如何解析HTML節點的屬性

<DIV myAttribute style="BORDER-BOTTOM: medium none; BACKGROUND-COLOR: transparent; BORDER-TOP: medium none" id=my_ID anotherAttribNamedDIV class="someclass"> 

請注意,屬性可以是
1.鍵= 「value」 對例如class="someclass"
2.鍵值對例如id=my_ID(無引號值)
3.普通屬性,例如myAttribute,它不具有「價值」

我需要將它們存儲到與鍵值對的字典如下
key=myAttribute value=""
key=style value="BORDER-BOTTOM: medium none; BACKGROUND-COLOR: transparent; BORDER-TOP: medium none"
key=id value="my_ID"
key=anotherAttribNamedDIV value=""
key=class value="someclass"

我找正則表達式來做到這一點。

+0

無法解析[X] HTML與正則表達式做到這一點。 http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Homam 2011-04-11 14:50:31

+0

不要爲你的html標籤使用大寫字母。 – David 2011-04-11 17:26:19

回答

10

您可以用HtmlAgilityPack

string myDiv = @"<DIV myAttribute style=""BORDER-BOTTOM: medium none; BACKGROUND-COLOR: transparent; BORDER-TOP: medium none"" id=my_ID anotherAttribNamedDIV class=""someclass""></DIV>"; 
HtmlDocument doc = new HtmlDocument(); 
doc.LoadHtml(myDiv); 
HtmlNode node = doc.DocumentNode.SelectSingleNode("div"); 

Literal1.Text = ""; 

foreach (HtmlAttribute attr in node.Attributes) 
{ 
    Literal1.Text += attr.Name + ": " + attr.Value + "<br />"; 
} 
-1
HtmlDocument docHtml = new HtmlWeb().Load(url); 
+2

您能否添加一些解釋(併爲代碼設置格式)? – 2014-12-26 17:51:09