加载中...

Python

  1. Home
  2. Computing & Technology
  3. Python

Part 3: Creating a Feed Class and Finishing the Python Program

By Al Lukaszewski, About.com

6 of 8

Getting the Titles and Links and Forming the Output

Now, to get the text out of the XML structure. First, here is the code:

linkdata = ""

for item in item_node:
     title = item.childNodes[1]
     link = item.childNodes[3]

     ftitle = title.firstChild.data
     flink = link.firstChild.data

    linkdata = linkdata + "[a href=\"" + flink + "\" target=\"target\"]" + ftitle + "[/a]
\n"

return linkdata

The first line is simply initiating a character string to which the iterator will eventually add.

As stated earlier, getElementsByTagName returns a list of nodes. Therefore, we can employ the same iteration techniques to this list as to others. For every item in the object item_node, we can make several assignments. Before we discuss them, if this loop business looks a bit fuzzy to you, review loops in my tutorial.

The next two assignments employ the attribute childNodes, an attribute of Node objects. Since item_node is really just a list of Node objects, we can iterate over the list and treat each item as a Node object. childNodes gives a list of the current node's children. If we know the format of the XML, we can call out and assign specific parts of the node at will. In this instance, we want the second and third elements of the list. These correspond to the title and link elements.

However, each of these assignments also include the XML markup tags, [title] and [link]. Obviously, this would feature poorly in a web page. To access just the text, we use an interface of the firstChild attribute; that interface is called data. data allows us to return just the text to a variable.

We can then use the two variables and some markup to build a string variable that holds the link data in HTML format. We then return linkdata.

6 of 8

Explore Python

More from About.com

Python

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.