from xml.dom import pulldom
def main():
events = pulldom.parse('orchid.xml')
for (event, node) in events:
if event == "START_ELEMENT" and node.tagName == "paragraph":
events.expandNode(node)
print node.getElementsByTagName("word")
if __name__ == '__main__':
main()
Pulldom นี่มันอารมณ์กึ่ง SAX กึ่ง DOM ถ้าเราไม่เรียก events.expandNode(node) มันก็จะไม่สร้าง DOM Tree ให้ก็ประหยัด memory ประหยัดเวลา ไม่เหมือน DOM ที่สร้าง tree ต้นใหญ่ทีเดียวทั้งเอกสารเลย
ตัวอย่าง
<corpus>
<document author=”abcd” …>
<paragraph>
<sentence raw_txt=”blaa blaa blaa”>
<word surface=”blaa” pos=”NNNN”/>
<word surface=”blaa” pos=”NNNN”/>
<word surface=”blaa” pos=”NNNN”/>
<word surface=”blaa” pos=”NNNN”/>
</sentence>
</paragraph>
<paragraph>
<sentence raw_txt=”blaa blaa blaa”>
<word surface=”blaa” pos=”NNNN”/>
<word surface=”blaa” pos=”NNNN”/>
<word surface=”blaa” pos=”NNNN”/>
<word surface=”blaa” pos=”NNNN”/>
</sentence>
</paragraph>
</document>
…
</corpus>
จาก code ตัวอย่าง และ XML ตัวอย่าง Pulldom มันก็จะสร้าง DOM tree ของส่วนที่เป็น สีเขียวก่อนในครั้งแรก ใช้เสร็จแล้วก็ปล่อยไป แล้วก็มาสร้างตรงสีน้ำเงินใหม่ แล้วก็ปล่อยไปอีก แบบนี้เราก็จะทำอะไรแบบ getElementsByTagName ซึ่งเป็นท่าของ DOM ในเฉพาะบริเวณ สีเขียว หรือ สีน้ำเงิน ได้ ซึ่งสำหรับผมมันก็สะดวกดี
ป.ล. แรงบรรดาลจากที่พี่ pok เคยถามไว้ ว่า Python มี Pull parser หรือเปล่า
ครั้งแรกโพสที่
http://veer.exteen.com/20070331/xml-pull-parser-python
มาแก้นิดๆ หน่อยๆ