找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 3085|回复: 0

[求助] 新手求助,python的XML处理

1

主题

1

帖子

7

积分

贫民

积分
7
711child 发表于 2014-6-17 11:01:59 | 显示全部楼层 |阅读模式
看了《python编程金典》第16章XML的处理,范例实现了一个论坛,论坛主页的程序如下:
#!c:\Python\python.exe
# Fig. 16.23: default.py
# Default page for message forums.

import os
import sys
from xml.dom.ext.reader import PyExpat

def printHeader( title, style ):
   print """Content-type: text/html

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC
   "-//W3C//DTD XHTML 1.0 Strict//EN"
   "DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">

<head>
<title>%s</title>
<link rel = "stylesheet" href = "%s" type = "text/css" />
</head>

<body>""" % ( title, style )

# open XML document that contains the forum names and locations
try:
   XMLFile = open( "../htdocs/XML/forums.xml" )
except IOError:
   print "Location: /error.html\n"
   sys.exit()

# parse XML document containing forum information
reader = PyExpat.Reader()
document = reader.fromStream( XMLFile )
XMLFile.close()

# write XHTML to browser
printHeader( "Bug2Bug Message Forums", "/XML/site.css" )
print """<h1>Bug2Bug Message Forums</h1>
<p style="font-weight:bold">Available Forums</p>
<ul>"""

# determine client-browser type
if os.environ[ "HTTP_USER_AGENT" ].find( "MSIE" ) != -1:
   prefix = "../XML/"   # Internet Explorer
else:
   prefix = "forum.py?file="

# add links for each forum
for forum in document.getElementsByTagName( "forum" ):

   # create link to forum
   link = prefix + forum.attributes.item( 0 ).value

   # get element nodes containing tag name "name"
   name = forum.getElementsByTagName( "name" )[ 0 ]

   # get Text node's value
   nameText = name.childNodes[ 0 ].nodeValue
   print '<li><a href = "%s">%s</a></li>' % ( link, nameText )

print """</ul>
<p style="font-weight:bold">Forum Management</p>
<ul>
   <li><a href = "addForum.py">Add a Forum</a></li>
   <li>Delete a Forum</li>
   <li>Modify a Forum</li>
</ul>
</body>

</html>"""

reader.releaseNode( document )

函数printHeader的定义中,print"""打印,最后有个<body>""",函数结束。此元素直到整个程序结尾才有结束标记:</body>。那么这段python语言和XML语言到底是怎么相互包含的呢,<body>是在函数外的吗?

初学python,请不吝赐教,谢谢!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表