如何解决使用 ElementTree 的 iter() 不带参数解析 XML,不返回文件中的前几个标签
我试图从 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 而不是实际的第一个标签。
先谢谢大家!
解决方法
您的输入文件不应在 XML 标记前包含“-”字符。 您应该至少删除根标记前面的第一个“-”,否则 发生解析错误。
还要注意,您的第一个打印标签名称没有首字母“{”,因此显然 您的列表发生了一些奇怪的事情,大概是在您的循环之后。
我运行了您的代码并得到了一个包含所有标签的正确列表。
尝试以下循环:
for elem in root.iter():
print(elem.tag)
也许它会给你一些关于错误真正原因的线索。
还考虑升级您的 Python 安装。也许你有 一些过时的模块。
另一个提示:在您包含的仅此输入上运行您的代码 在您的帖子中,内容替换为“***”。也许真正的原因 您的错误出现在任何源元素的实际内容中 (你在这里用星号代替了它)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。