簡體   English   中英

如何讀取單個XML項目

[英]How can I read a single XML item

我嘗試使用本教程中的這個示例(這里是一個鏈接 ):

#!/usr/bin/python

import xml.sax

class MovieHandler( xml.sax.ContentHandler ):
   code........
if ( __name__ == "__main__"):

   # create an XMLReader
   parser = xml.sax.make_parser()
   # turn off namepsaces
   parser.setFeature(xml.sax.handler.feature_namespaces, 0)

   # override the default ContextHandler
   Handler = MovieHandler()
   parser.setContentHandler( Handler )

   parser.parse("movies.xml")

將結果作為輸出:

*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Year: 2003
Rating: PG
Stars: 10
Description: Talk about a US-Japan war
*****Movie*****
Title: Transformers
Type: Anime, Science Fiction
Format: DVD
Year: 1989
Rating: R
Stars: 8
Description: A schientific fiction
*****Movie*****
Title: Trigun
Type: Anime, Action
Format: DVD
Rating: PG
Stars: 10
Description: Vash the Stampede!
*****Movie*****
Title: Ishtar
Type: Comedy
Format: VHS
Rating: PG
Stars: 2
Description: Viewable boredom

假設我只想要這個結果:

*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Year: 2003
Rating: PG
Stars: 10

或這個

****Movie*****
    Title: Enemy Behind
    Type: War, Thriller
    Rating: PG
    Stars: 10

我可以做些什么? 我剛剛開始學習python和XML:

可以通過解析XML來創建DOM樹來完成這種事情,然后可以很容易地以隨機訪問方式進行查詢。

例如,要打印標題為“敵人,背后”的電影,您可以執行以下操作:

#!/usr/bin/python

from xml.dom.minidom import parse
import xml.dom.minidom

# Open XML document using minidom parser
DOMTree = xml.dom.minidom.parse("movies.xml")
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
    print "Root element : %s" % collection.getAttribute("shelf")

# Get all the movies in the collection
movies = collection.getElementsByTagName("movie")

# Print detail of each movie.
for movie in movies:
    title = movie.getAttribute("title")
    if title == "Enemy Behind":
         print "*****Movie*****"
         print "Title: %s" % title

         type = movie.getElementsByTagName('type')[0]
         print "Type: %s" % type.childNodes[0].data
         format = movie.getElementsByTagName('format')[0]
         print "Format: %s" % format.childNodes[0].data
         rating = movie.getElementsByTagName('rating')[0]
         print "Rating: %s" % rating.childNodes[0].data
         description = movie.getElementsByTagName('description')[0]
         print "Description: %s" % description.childNodes[0].data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM