C# 从HTML文本中获取属性值的最佳方法
我有下面的C# 从HTML文本中获取属性值的最佳方法,c#,html,c#-3.0,C#,Html,C# 3.0,我有下面的 <INPUT type=hidden value=2 name=hidItemCount> <INPUT type=hidden value="2;undefined;1;SR;Name=Created 12-May-10;Use Selected=; DS Mnemonic=L#%%902;List Size=2;Created=Aug 6 2009 ;Amended=May 12 2010 ;|undefined;1;SR;Name=Created 12-May
<INPUT type=hidden value=2 name=hidItemCount>
<INPUT type=hidden value="2;undefined;1;SR;Name=Created 12-May-10;Use Selected=;
DS Mnemonic=L#%%902;List Size=2;Created=Aug 6 2009 ;Amended=May 12 2010 ;|undefined;1;SR;Name=Created 12-May-10;
Use Selected=;DS Mnemonic=L#ABCD12;List Size=2;Created=Apr 15 2010 ;Amended=May 12 2010 ;|" name=hidItemData>
使用C#3.0,下面的代码片段使用正则表达式返回助记符的所有值
Regex r;
Match m;
r = new Regex(@"Mnemonic=(\S*);",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (m = r.Match(source); m.Success; m = m.NextMatch())
{
Console.WriteLine(m.Groups[1] + " at "
+ m.Groups[1].Index);
}
(\S*);表示查找以;结尾的零个或多个非空格字符 公共静态列表getProperty(HtmlDocument文档、字符串元素、字符串属性、字符串值){
HtmlElementCollection elems=document.GetElementsByTagName(元素);
List ret=新列表();
foreach(元素中的HtmlElement元素){
字符串valueAtr=elem.GetAttribute(属性);
如果(!String.IsNullOrEmpty(valueAtr)){
var pos=价值指数(价值);
而(位置!=-1){
valueAtr=valueAtr.Substring(pos+value.Lenght+1);/L#%%902;列表大小=2;Cr
res.Add(valueAtr.SubString(valueAtr.indexof(';'));
pos=数值索引OF(数值);
}//而
}//如果
}//为了
返回ret;
}
我不确定这项工作是否100%的索引可能是错误的
Regex r;
Match m;
r = new Regex(@"Mnemonic=(\S*);",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (m = r.Match(source); m.Success; m = m.NextMatch())
{
Console.WriteLine(m.Groups[1] + " at "
+ m.Groups[1].Index);
}
public static List<String> getProperty(HtmlDocument document, string element, string attribute, string value) {
HtmlElementCollection elems = document.GetElementsByTagName(element);
List<String> ret = new List<String>();
foreach(HtmlElement elem in elems) {
String valueAtr = elem.GetAttribute(attribute);
if(!String.IsNullOrEmpty(valueAtr)) {
var pos = valueAtr.indexOf(value);
while(pos != -1) {
valueAtr = valueAtr.Substring(pos + value.Lenght + 1); // L#%%902;List Size=2;Cr
res.Add(valueAtr.SubString(valueAtr.indexof(';')));
pos = valueAtr.indexOf(value);
} //while
} //if
} // for