【问题标题】:Parse second XML element in Python在 Python 中解析第二个 XML 元素
【发布时间】:2018-08-13 20:26:15
【问题描述】:

我有一个格式如下的 XML 文件:

<item id="xxxxxx">
    <Category>xxxxx</Category>
    <EmpEmail>xxxxxx</EmpEmail>
    <EmployeeName>xxxxxxx</EmployeeName>
    <InteractionType>xxxxxx</InteractionType>
    <pxCreateOpName>xxxxxx</pxCreateOpName>
    <pyID>xxxxx</pyID>
    <WorkerInfo>
        <Country>xxxxx</Country>
        <JobTitle>xxxxxx</JobTitle>
        <Region>xxxxx</Region>
    </WorkerInfo>
    <InsKey>xxxxx</InsKey>
</item>

我可以使用

解析项目元素中的标签
for item in root.findall('item'):
    row = []
    if item.find('Category') is not None:
        category = item.find('Category').text
    else:
        category = ''
    row.append(category)

但我无法使用for item in root.findall('WorkerInfo') 检索 WorkerInfo 下的标签。到达这个元素的最佳方法是什么?

【问题讨论】:

标签: python xml parsing


【解决方案1】:

只需添加另一个循环,如下所示。我的缩进也可能关闭。

for item in root.findall('item'):
row = []
if item.find('Category') is not None:
    category = item.find('Category').text
else:
     for itemsecond in root.findall('WorkerInfo'):
         if item.find('WorkerInfo') is not None:
             category2= item.find('Category').text
             if category2 is not None:
                row.append(category2)
row.append(category)

【讨论】:

    【解决方案2】:

    看起来 WorkerInfo 包含嵌套元素,而您的第一行 for item in foot.findall('item'): 只会循环顶级元素。因此,在某些时候item 将设置为 WorkerInfo,但这与设置为其子元素不同。您将需要一个嵌套循环来循环这些。试试这个:

    for item in root.findall('item'):
        for workerItem in item.findall('WorkerInfo'):
            // Do whatever you want with the elements of WorkerInfo here
    

    【讨论】:

      【解决方案3】:

      要到达WorkerInfo 并检索其标签,您可以使用类似的结构。只需调用 findall() 并传入 'WorkerInfo' 并循环遍历其子项。

      for item in root.findall('item'):
          for worker in root.findall('WorkerInfo'):
              row = []
              for child in worker:
                  row.append(child.tag)
      

      在您的示例中,row 变为 ['Country', 'JobTitle', 'Region']

      【讨论】:

        猜你喜欢
        • 2013-03-28
        • 1970-01-01
        • 2020-09-20
        • 1970-01-01
        • 2019-10-26
        • 2012-02-16
        • 1970-01-01
        • 1970-01-01
        • 2017-10-09
        相关资源
        最近更新 更多