0
<?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>

I'm trying to access First_Name, Last_Name, Headline and Some_city, STATE

So far I have:

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

for child in root:
  print child

Which prints out:

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

How can I access the value of 'first-name'?

1 Answer 1

2

Get the .text property:

for child in root:
    print child.text
Sign up to request clarification or add additional context in comments.

5 Comments

is there a way to specifically say "Just give me 'first-name'?
@MorganAllen yup, root[0].text, for example.
@MorganAllen or, root.findtext('first-name').
in the instance where the name is nested in location, how would I navigate to that?
@MorganAllen you can use an xpath expression: print tree.findtext('.//location/name').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.