0

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']

1 Answers1

0

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

MindSwipe
  • 7,193
  • 24
  • 47