2016-12-07 32 views
1

我有一个XML文件:解析XML的Python:多相同的属性

<movie title="Enemy Behind"> 
     <type>War, Thriller</type> 
     <type>WW2</type> 
     <format>DVD</format> 
     <year>2003</year> 
     <rating>PG</rating> 
     <stars>10</stars> 
     <description>Talk about a US-Japan war</description> 
    </movie> 

,我使用下面的代码来解析这个XML在Python:

 Print detail of each movie. 
    for movie in movies: 
     print ("*****Movie*****") 
     if movie.hasAttribute("title"): 
      print ("Title: %s" % movie.getAttribute("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) 

但仅使用此代码其中一个属性被打印,即“战争,惊悚片”。 “WW2”的另一个属性没有打印。

我应该使用for循环吗?我已经尝试过,并且出现错误“'元素'对象不可迭代”。

+0

这说明了什么?打印类型(movie.getElementsByTagName('type')) – Bemmu

回答

2

我不知道你使用的是什么库,但你能得到的值与下面的代码的XML片段:

的test.xml

<movie title="Enemy Behind"> 
     <type>War, Thriller</type> 
     <type>WW2</type> 
     <format>DVD</format> 
     <year>2003</year> 
     <rating>PG</rating> 
     <stars>10</stars> 
     <description>Talk about a US-Japan war</description> 
    </movie> 

test.py

import lxml.etree 

# Getting the XML root tag... Movie in our case 
root = lxml.etree.parse("test.xml").getroot() 

# the method "get" returns the value of the XML attribute informed 
# as parameter 
print(root.get("title")) 

# You can iterate over the children of an XML node 
for child in root: 
    print(child.text) # gets the text value from the children XML nodes 

# Or more specifically, for each type, use the method FIND to get 
# the XML child node from the current XML node. 
node = root.find("name") 
if node is not None: 
    print(node.text) 

# ..Or if you expect more than one node, as it is the case for the tag 
# "type", you can use FINDALL which returns all direct children from the current XML node. 
nodes = root.findall("type") 
for node in nodes: 
    print(node.text) 

推荐阅读:

+0

伴侣我在看你给我的教程,他们似乎很好。我正试图设计我自己的做法。将尽快发布我用过的东西。 –

+0

@NikhileshSharma我发布的代码片段应该可以帮助你,但强烈推荐阅读参考资料:)如果你认为我以任何方式帮助你,请考虑upvoting /接受我的答案:) –

+0

伙伴我正在尝试不同的东西>我可能会为它做一个新的职位。 –