[英]Best way to get the attribute value from HTML text
I have the below 我有以下
<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>
From this I need to find out the values for DS Mnemonic which is 由此,我需要找出DS助记符的值是
L#%%902 and L#ABCD12
. L#%%902 and L#ABCD12
。 in this case 在这种情况下
What is the best way to go ahead with this? 进行此操作的最佳方法是什么? Any regular expression?
任何正则表达式?
My approach so far is 到目前为止,我的方法是
string source = "<INPUT type=hidden value=2 name=hidItemCount>";
source += "<INPUT type=hidden value=2;undefined;1;SR;Name=Created 12-May-10;Use Selected=;";
source +="DS Mnemonic=L#%%902;List Size=2;Created=Aug 6 2009 ;Amended=May 12 2010 ;|undefined;1;SR;Name=Created 12-May-10;";
source +="Use Selected=;DS Mnemonic=L#ABCD12;List Size=2;Created=Apr 15 2010 ;Amended=May 12 2010 ;| name=hidItemData> ";
string[] seperator = new string[] { "DS Mnemonic=" };
string[] arr1 = source.Split(seperator, StringSplitOptions.None).Skip(1).ToArray();
//final result
string[] arr2 = arr1.ToList().Select(i => i.Split(';').First()).ToArray();
Using C#3.0 使用C#3.0
The following code snippet returns all values for Mnemonic using regex 以下代码段使用正则表达式返回助记符的所有值
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*); (\\ S *); means that you look for zero or more occurrences of non-space characters that end with ;
表示您寻找零个或多个以结尾的非空格字符; .
。
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
return ret; 返回ret }
}
I'm not sure that this work for 100% the indexes might be wrong. 我不确定这对于100%的索引是否可能是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.