使用 python 从 xml 打印标签值

print tag value from xml using python

我正在尝试编写一个 Python 脚本,在 XML 输出中打印特定标签的值。在这里,我需要打印的标签值是 XML 输出中每次出现的值。我尝试如下,但它显示属性错误。这里有什么问题?获取和打印我感兴趣的某些更多标签的值的正确方法是什么?有什么帮助吗?谢谢。

import xml.etree.ElementTree as ET

mystring="""<?xml version="1.0" encoding="UTF-8"?>
<main>
    <student>
        <male>
            <result>pass</result>
            <name>Paul</name>
            <address>boston</address>
            <localreference>
                <name>Charlie</name>
            </localreference>
        </male>
        <female>
            <result>pass</result>
            <name>Rose</name>
            <address>newyork</address>
            <localreference>
                <name>Charlie</name>
            </localreference>
        </female>
    </student>
    <student>
        <male>
            <result>fail</result>
            <name>Philippe</name>
            <address>boston</address>
            <localreference>
                <name>White</name>
            </localreference>
        </male>
    </student>
</main>"""

main = ET.fromstring(mystring)
for student in main:
  if (student.tag == "student"):
      print student.find("male/result").text
      print student.find("female/result").text

错误>

# python new5.py
pass
pass
fail
Traceback (most recent call last):
  File "new5.py", line 39, in <module>
    print student.find("female/result").text
AttributeError: 'NoneType' object has no attribute 'text'

您用于打印标签值的代码是正确的,但您要求的 xml 部分不存在。第二学生区没有女区。这就是为什么 student.find("female/result") 在第二个学生身上返回 None,而你不能在 None 对象上调用 .text

ElementTree 支持 XPath 的一个子集,这对于您的示例来说可能更容易:

root = ET.fromstring(mystring)
for gender in ('male', 'female'):
    print gender
    for student in root.findall('./student/%s' % gender): 
        print '\t{:20}: {}'.format(student.find('name').text, student.find('result').text)

打印:

male
    Paul                : pass
    Philippe            : fail
female
    Rose                : pass

(顺便说一句:避免使用 main 作为变量名,因为你破坏了 main 模块的名称)


如果您希望结果按文档顺序排列而不是按性别分组,您可以这样做:

for students in root.findall('./student'):
    for gender in students:
        print ' '.join([gender.tag] + map(lambda a: gender.find(a).text, ('name', 'address', 'result', 'localreference/name')))

版画

male Paul boston pass Charlie
female Rose newyork pass Charlie
male Philippe boston fail White