万事开头难。
想要找一个例子看看如何用python来将一些数据生成一个.xml文件真不容易。昨天基本上是怎么也没干成,算是今天的铺垫吧。用百度我是没找到 有用的信息,只有一篇似乎有点用处,作者说他的程序可以运行,可根本不是那么回事。这样的例子找不到的原因可能是大虾没时间写,菜鸟不会写。还是 google好用,也是,外国的东西确实比较好(我很爱国的,别骂我!),他们的程序员也有闲心也有时间写这样的小程序,如果没有这样的程序,初学者真不 知道怎么入门。
Creating XML With Python
Part 1: xml.dom.minidom Basics
There are many resources out there if you’d like to consume and parse XML with Python. I was looking around the web for resources on producing XML with Python, and I wasn’t able to find much. Here is a pretty simple script and its output. It will create a WML document.
from xml.dom.minidom import Document # Create the minidom document
doc = Document()
# Create the base element
wml = doc.createElement(“wml”)
doc.appendChild(wml)
# Create the main element
maincard = doc.createElement(“card”)
maincard.setAttribute(“id”, “main”)
wml.appendChild(maincard)
#Create aelement
paragraph1 = doc.createElement(“p”)
maincard.appendChild(paragraph1)
# Give theelemenet some text
ptext = doc.createTextNode(“This is a test!”)
paragraph1.appendChild(ptext)
# Print our newly created XML
print doc.toprettyxml(indent=” “)
(This code was highlighted by Gnu source-highlight. You can grab a text version here.) Here’s what the above code produces:
This is a test!
As an aside, this XML will probably not parse on a WAP/WML mobile device, as it doesn’t have a DOCTYPE.
You can see that creating arbitrary XML with the minidom is nearly trivial. I didn’t say intuitive, I said nearly trivial. I’m sure that there are better ways of producing XML, but right now the documentation and tutorials are weak at best. Stay tuned for more.
来自于:http://www.postneo.com/projects/pyxml/
这些信息已经足够用了。
程 序组织的思维方式与表现形式和Java没有什么大的区别,都是先生成一个个对象(Java中这么说,python没看过中文资料,不知道怎么称呼,英文的 我也不知道,是element??),再添加,和创建JavaGUI界面时的感觉一样,new完了add,一个容器装另一个容器或部件。
会了就感觉不到难度了,现在我已经可以把一个页面的信息生成为.xml了,下面马上要做的是在同一个.xml文件中生成第二个结构相同的element.然后就要写新的程序,可以自动将多个页面的信息都生成xml格式,放到一个或多个.xml文件中。
估计当这些做完了,就应该学习怎么parse xml了,这样的信息很好找, 到处都是。然后写程序将分离出来的信息分别存入数据库中的相应的字段中,然后还需要写动态页面,将数据库中的内容表现出来。时间不多了,我也不确定自己能不能完成这些,还要更努力才行。