简体   繁体   中英

How to retrieve value of attribute from element in c#

I have below html element, and I want to get the value of attribute "data-productid"

<div qa-id="itemImageContainer" class="items__img oli-image js-oli-image zoom_on_hover" ng-class="{'zoom_on_hover': oli.IsNewPreviewEnabled === true}" data-action="edit" data-oli-index="0" data-productid="2940" data-complete="false" data-design-name="" data-tid="27dff633-049f-44c8-bab8-40e3bd533feb" data-productsku="2940">

XPath

//*[@qa-id = 'itemImageContainer']

Most HTML is XML compliant ( a list of some exceptions ) so you should be able to parse an XElement from your string and get the value like so:

var element = XElement.Parse(divString);
// The return value of 'Attribute(...)' can be null, so maybe do null checking
var dataProductId = element.Attribute("data-productid").Value;

If you run into some HTML that is not valid XML, you'll probably need something like the Html Agility Pack to properly parse your HTML. Using it your code would like this:

var html = new HtmlDocument();
html.Load(htmlString);
var div = html.DocumentNodes.SelectNodes("//*[@qa-id = 'itemImageContainer']").LastOrDefault();
// Maybe check if its null
var dataProductId = div.Attributes["data-productid"].Value;

I don't have a lot of experience working with XPath, so I got my example from this answer

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