简体   繁体   中英

How would I get a little piece of HTML code out of a string? C#

I am trying to get a select HTML field out of my C# application.

The HTML that can come in are as follows...

<HTML>
    <BODY BGCOLOR="#123456">
        HELLO
    </BODY>
</HTML>

This HTML can change anytime, the part of the HTML I want is the value for BGCOLOR eg #123456

or it could be "white", or "red", etc...

How can I do this?

I don't think substring would work as i can't predict how long the field would be.

Thanks

you can use Html Agility Pack for parsing HTML.

So parsing something like BGCOLOR might look like:

var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(someHtml);

var body = htmlDoc.DocumentNode.SelectSingleNode("//body");
string bgColor = body.Attributes["bgcolor"].Value;

You need to use an XPath query.

see http://support.microsoft.com/kb/308333

Load the HTML into an XmlDocument and query it using "HTML/BODY@BGCOLOR"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM