Search code examples
delphihtml-parsingmshtml

Delphi html parsing check if element has attribute


I have the following procedure:

class procedure ParseData(AData: string; var ATextList: TList<string>);
var
  HTMLDoc: OleVariant;
  HTMLElement: OleVariant;
  I: Integer;
begin
  HTMLDoc := coHTMLDocument.Create as IHTMLDocument2;
  HTMLDoc.Write(AData);
  HTMLDoc.Close;

  for I := 0 to HTMLDoc.body.all.length - 1 do
  begin
    HTMLElement := HTMLDoc.body.all.item(I);

    if HTMLElement.hasAttribute('attr1') then
      ATextList.Add(HTMLElement.innerHTML);
  end;
end;

The problem is that hasAttribute is not working. Funtions and proicedures like setattribute, innerHTML, tagName are working fine. Is there another way to check if an element contains given attribute?


Solution

  • You could test for:

    if not VarIsNull(HTMLElement.getAttribute('attr1')) then
      ATextList.Add(HTMLElement.innerHTML);
    

    EDIT:

    hasAttribute is implemented in IHTMLElement5 interface - it requires IE8 and later, and is not supported in IE7 Standards mode or IE5 (Quirks) mode.

    I imported C:\Windows\System32\mshtml.tlb (with tlibimp tool), and this code works:

    if (IDispatch(HTMLElement) as IHTMLElement5).hasAttribute('attr1') then...