Delphi - XML - childnodes - getting attributes

Dan Shelton picture Dan Shelton · Jul 5, 2009 · Viewed 19.4k times · Source

I am trying to get the correct data from a twitter atom/xml feed. I have the twitter data in a txmldocument and am trying to get some specific information from it.

Here is a truncated example of the data:

<entry>
  <link type="text/html" rel="alternate" href="http://twitter.com/blub/statuses/1501068" /> 
  <title>title of twitter post goes here</title> 
  <link type="image/png" rel="image" href="http://s3.amazonaws.com/twitter_production/profile_images/234870532/normal.jpg" /> 
</entry>

The problem I have is that I am trying to get the profile image url (the href attribute of the second link tag).

If I use code like this:

i:=xmldocument1.DocumentElement.ChildNodes['entry'];
text:=(i.ChildNodes['link'].GetAttributeNS('href',''));

What I get is the href value of the FIRST link tag, but I want the SECOND link tag, and I don't know exactly how to do that. Does anybody have any ideas?

thanks.

Answer

Nick Dandoulakis picture Nick Dandoulakis · Jul 5, 2009

You could do this:

i := xmldocument1.DocumentElement.ChildNodes['entry'];
text := (i.ChildNodes[2].GetAttributeNS('href','')); // notice the [2] index

because ChildNodes is an IXMLNodeList object. Make sure that you check if node '2' exists and if it has the type="image/png" property - always validate your data.

Here is a part of the Delphi documentation,

property Nodes[const IndexOrName: OleVariant]: IXMLNode; default;

Description

Read Nodes to access a specified node in the list.

IndexOrName identifies the desired node. It can be

  • The index of the node, where 0 is the index of the first node, 1 is the index of the second node, and so on. The Count property provides an upper bound on the indexes you can specify.
  • The LocalName property of a node in the list.

If IndexOrName does not identify a node in the list, and if the document that contains this node list’s parent includes doNodeAutoCreate in its Options property, then the node list tries to create a new node with the name specified by IndexOrName. If the node list can’t create the new node, it raises an exception.