开发者

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

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


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*); 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; }

I'm not sure that this work for 100% the indexes might be wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜