abbas
abbas

Reputation: 432

C# cast simple html string to an html object

I have the following string

     string myHtml="<input type='text' value='123' class='myClass'></input>";

I want to read or cast myHTML into some sort of C# HTML object so I can do something like:

    DesiredHTMLClass obj=new DesiredHTMLClass(myHTML);
    string val=obj.value;  //Would return 123
    string mClass=obj.class; //Would return myclass

I cannot use something like the HTML Agility Pack,simple C#

Thanks

Upvotes: 0

Views: 1856

Answers (2)

kprobst
kprobst

Reputation: 16651

If you can only use 'simple C#' then you'll have to parse the string manually, which won't be fun, but I suppose it's possible. Also, it will be difficult to expose attributes as concrete properties of the parsed object.

What you can do is use something like an SGML reader to convert the snippet to XML and then read it; if your HTML is well-formed and you know it will always be then you can skip the SGML step and use something like Linq2XML to parse it directly, although you still won't get an object with properties but rather you'll have to query the attribute values and so on.

Upvotes: 0

Israel Lot
Israel Lot

Reputation: 653

You can use regex to detect tags and map attributes to properties of Html objects. But it's a painful work.

Edit: If you need only a small number of tags and you know it in advance you can parse it with Regex. If you need to parse the whole html you are in trouble.

Upvotes: 1

Related Questions