在Python中解析XML时访问元素的值

时间:2014-08-15 17:59:09

标签: python xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
  <first-name>First_Name</first-name>
  <last-name>Last_Name</last-name>
  <headline>Headline</headline>
  <location>
    <name>Some_city, STATE </name>
    <country>
      <code>us</code>
    </country>
  </location>
</person>

我试图访问First_Name,Last_Name,标题和Some_city,状态

到目前为止,我有:

import xml.etree.ElementTree as ET
tree = ET.parse(data)
root = tree.getroot()

for child in root:
  print child

打印出来:

<Element 'first-name' at 0x110726b10>
<Element 'last-name' at 0x110726b50>
<Element 'headline' at 0x110726b90>
<Element 'location' at 0x110726bd0>

如何访问&#39; first-name&#39;?

的值

1 个答案:

答案 0 :(得分:2)

获取.text属性:

for child in root:
    print child.text