如何使用python从xml文件中提取文本

2024-10-04 05:23:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从这个xml文件中提取文本数据,但我不知道为什么我的代码不起作用。我怎样才能得到这个电话号码?请看一下这个XML文件和我的代码格式。我正试图从这个标记中提取数据。提前谢谢:)

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

这是我的python代码

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)

Tags: 文件数据代码orguserootxmlcountry
1条回答
网友
1楼 · 发布于 2024-10-04 05:23:01

您的XML文档已指定名称空间,因此它类似于:

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

输出:

tel:+1(303)-554-8889

相关问题 更多 >