Picking multiple values between tags

Asked

Viewed 642 times

2

I need to pick a value between the tags of a text, so I found here on the site the function:

function ExtractText(aText, OpenTag, CloseTag : String) : String;

It worked perfectly, but with only the first value found.

But if I have more Tags equal, to add all values within these Tags equal in a Listbox, as I should, because I did not find anywhere. Example:

<t1>teste1</t1>
<t2>teste2</t2>
<t1>teste3</t1>
<t1>teste4</t1>
<t3>teste5</t3>

If I took the tags t1 and /t1, I wanted to display it like this in Listbox:

teste1
teste3
teste4
  • Have you ever thought about doing this in a loop? In while for example. This could be done throughout the listbox and return only when there is the tag for example.

1 answer

2

The function below scans a text, and checks on a loop if the current element contains the tag, if you have, add in the Stringlist. This information is obtained through the interface IHTMLDocument2.

// Incluir em Uses: ActiveX, MSHTML   
Function ParseTag(Const Texto, Tag: string): TStringList;
Var
 Doc, Elementos: OleVariant;
 I: integer;
begin
  Doc := CoHTMLDocument.Create as IHTMLDocument2;
  try      
    Result := TStringList.Create;
    Doc.write(Texto);

    for I := 0 to Doc.body.all.length - 1 do begin
      Elementos := Doc.body.all.item(I);
      if Elementos.tagName = Tag then
        Result.Add(string(Elementos.innerText));
    end;
  finally
    Doc.close;
  end;
end;

To use it call at the event OnClick() one-button:

procedure TForm1.Button1Click(Sender: TObject);
begin
ListBox1.Items.AddStrings(ParseTag('HTML aqui', 'H1'));
end;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.