python - 在Python中解析XML : Multiple same attributes

标签 python xml

我有一个 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>

我使用以下代码在 Python 中解析此 XML:

     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)

但是使用此代码只会打印其中一个属性,即“ war ,惊悚片”。另一个显示“WW2”的属性不会被打印。

我应该使用for循环吗?我已经尝试过,但收到错误“'Element'对象不可迭代”。

最佳答案

我不知道您正在使用什么库,但您可以使用以下代码获取 XML 片段的值:

测试.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>

测试.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)

推荐阅读:

关于python - 在Python中解析XML : Multiple same attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41008297/

相关文章:

python - 使用python ElementTree,如何向具有命名空间的树添加节点?

xml - 如何为具有属性和内容的元素指定XML结构标签?

xml - XPath函数:包含错误(如果使用的话)!

python - 如何在 Pandas 列字符串中插入空格

python - 如何防止 Python 在数据库连接失败时退出?

python - 覆盖 -Class 属性 - getter

python - 为什么 "is not None"不能与 dataframe.loc 一起使用,但 "!= None"可以正常工作?

php - 来自 PHP 的 crypt() 的 MD5 散列密码是否可以移植到 Django 密码字段?

c# - 如何在 C# 中解析 XML 文件(youtube api 结果)?

php - 将 XML 文件元素转换为 PHP 数组