首页 > 解决方案 > 使用不带参数的 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 而不是实际的第一个标签。

提前谢谢大家!

标签: pythonxmllistxml-parsingelementtree

解决方案


您的输入文件不应在 XML 标记前包含“-”字符。您应该至少删除根标记前面的第一个“-”,否则会发生解析错误。

另请注意,您的第一个打印标签名称没有初始“{”,因此显然您的列表发生了一些奇怪的事情,大概是您的循环之后。

我运行了您的代码并得到了一个正确的列表,其中包含所有标签。

尝试以下循环:

for elem in root.iter():
    print(elem.tag)

也许它会给你一些关于你错误的真正原因的线索。

还可以考虑升级您的Python安装。也许你有一些过时的模块。

另一个提示:仅在您包含在帖子中的这个输入上运行您的代码,内容替换为“***”。也许你的错误的真正原因是任何源元素的实际内容(你在这里用星号替换)。


推荐阅读