【发布时间】:2021-04-22 06:46:26
【问题描述】:
我正在尝试从 XML 文件中提取所有标头并将它们放入 python 中的列表中,但是,每次我运行我的代码时,从文件中提取的第一个标签实际上并不是 XML 文件中的第一个标签。相反,它从第 18 个标签开始,然后从那里打印列表的其余部分。真正奇怪的部分是,当我最初编写此代码时,它按预期工作,但是当我添加代码以提取元素文本并将其放入列表中时,标头代码停止工作,无论是在原始程序中还是在下面的独立代码中.我还应该提到完整的程序不会以任何方式操作 XML 文件。提取后,所有操作都仅在 python 列表上完成。
import xml.etree.ElementTree as ET
tree = ET.parse("Sample.xml")
root = tree.getroot()
headers = [elem.tag for elem in root.iter()]
print(headers)
Sample.XML 是一个敏感文件,所以我必须编辑所有元素文本。它也是一个非常大的文件,所以我只包含了一个帐户的元素。
-<ExternalCollection xmlns="namespace.xsd">
-<Batch>
<BatchID>***</BatchID>
<ExternalCollectorName>***</ExternalCollectorName>
<PrintDate>***</PrintDate>
<ProviderOrganization>***</ProviderOrganization>
<ProvOrgID>***</ProvOrgID>
-<Account>
<AccountNum>***</AccountNum>
<Guarantor>***</Guarantor>
<GuarantorAddress1>***</GuarantorAddress1>
<GuarantorAddress2/>
<GuarantorCityStateZip>***</GuarantorCityStateZip>
<GuarantorEmail/>
<GuarantorPhone>***</GuarantorPhone>
<GuarantorMobile/>
<GuarantorDOB>***</GuarantorDOB>
<AccountID>***</AccountID>
<GuarantorID>***</GuarantorID>
-<Incident>
<Patient>***</Patient>
<PatientDOB>***</PatientDOB>
<FacilityName>***</FacilityName>
-<ServiceLine>
<DOS>***</DOS>
<Provider>***</Provider>
<Code>***</Code>
<Modifier>***</Modifier>
<Description>***</Description>
<Billed>***</Billed>
<Expected>***</Expected>
<Balance>***</Balance>
<SelfPay>***</SelfPay>
<IncidentID>***</IncidentID>
<ServiceLineID>***</ServiceLineID>
-<OtherActivity>
</OtherActivity>
</ServiceLine>
</Incident>
</Account>
</Batch>
</ExternalCollection>
输出如下:
'namespace.xsd}PatientDOB', '{namespace.xsd}FacilityName', '{namespace.xsd}ServiceLine', '{namespace.xsd}DOS', '{namespace.xsd}Provider', '{namespace.xsd}Code', '{namespace.xsd}Modifier', '{namespace.xsd}Description', '{namespace.xsd}Billed', '{namespace.xsd}Expected', '{namespace.xsd}Balance', '{namespace.xsd}SelfPay', '{namespace.xsd}IncidentID', '{namespace.xsd}ServiceLineID', '{namespace.xsd}OtherActivity'
如您所见,由于某种原因,第一个返回值是 Patient DOB 而不是实际的第一个标签。
提前谢谢大家!
【问题讨论】:
标签: python xml list xml-parsing elementtree