booleantrue
booleantrue

Reputation: 129

How to extract text from xml file using python

I'm trying to extract text data from this xml file but I don't know why my code not working. How do I get this phone number? Please have a look at this XML file and my code format as well.I'm trying to extract data from this tag Thank you in advance :)

<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:voc="urn:hl7-org:v3/voc" xmlns:sdtc="urn:hl7-org:sdtc" xsi:schemaLocation="CDA.xsd">
  <realmCode code="US"/>
  <languageCode code="en-US"/>
  <recordTarget>
    <patientRole>
      <addr use="HP">
        <streetAddressLine>3345 Elm Street</streetAddressLine>
        <city>Aurora</city>
        <state>CO</state>
        <postalCode>80011</postalCode>
        <country>US</country>
      </addr>
      <telecom value="tel:+1(303)-554-8889" use="HP"/>
      <patient>
        <name use="L">
          <given>Janson</given>
          <given>J</given>
          <family>Example</family>
        </name>
      </patient>
    </patientRole>
  </recordTarget>
</ClinicalDocument>

Here is my python code

import xml.etree.ElementTree as ET

tree = ET.parse('country.xml')
root = tree.getroot()
print(root)

for country in root.findall('patientRole'):
    number = country.get('telecom')
    print(number)

Upvotes: 1

Views: 569

Answers (1)

perl
perl

Reputation: 9941

Your XML document has namespace specified, so it becomes something like:

for country in tree.findall('.//{urn:hl7-org:v3}patientRole'):
    number = country.find('{urn:hl7-org:v3}telecom').attrib['value']
    print(number)

Output:

tel:+1(303)-554-8889

Upvotes: 4

Related Questions