首页 > 解决方案 > python - 如何在python中获取给定特定属性的父母和祖父母标签?

问题描述

我有一个结构像这样的 xml:

<cat>
  <foo>
    <fooID>1</fooID>
    <fooName>One</fooName>
    <bar>
      <barID>a</barID>
      <barName>small_a</barName>
      <barClass>
        <baz>
          <qux>
            <corge>
              <corgeName>...</corgeName>
              <corgeType>
                <corgeReport>
                  <corgeReportRes Reference="x" Channel="High">
                    <Pos>1</Pos>
                  </corgeReportRes>
                </corgeReport>
              </corgeType>
            </corge>
          </qux>
        </baz>
      </barClass>
    </bar>
    <bar>
      <barID>b</barID>
      <barName>small_b</barName>
      <barClass>
        <baz>
          <qux>
            <corge>
              <corgeName>...</corgeName>
              <corgeType>
                <corgeReport>
                  <corgeReportRes Reference="y" Channel="High">
                    <Pos>1</Pos>
                  </corgeReportRes>
                </corgeReport>
              </corgeType>
            </corge>
          </qux>
        </baz>
      </barClass>
    </bar>
  </foo>
  <foo>
    <fooID>2</fooID>
    <fooName>Two</fooName>
    <bar>
      <barID>c</barID>
      <barName>small_c</barName>
      <barClass>
        <baz>
          <qux>
            <corge>
              <corgeName>...</corgeName>
              <corgeType>
                <corgeReport>
                  <corgeReportRes Reference="z" Channel="High">
                    <Pos>1</Pos>
                  </corgeReportRes>
                </corgeReport>
              </corgeType>
            </corge>
          </qux>
        </baz>
      </barClass>
    </bar>
  </foo>
</cat>

而且,我想获取具有属性节点的特定父/祖父/祖父标记的值Channel="High"。我只想获取 fooID 值、fooName 值、barID 值、barName 值。

我在 Python 3 中有以下代码:

import xml.etree.ElementTree as xmlET

root = xmlET.parse('file.xml').getroot()
test = root.findall(".//*[@Channel='High']")

这实际上给了我一个匹配的元素列表,但是,我仍然需要特定父母/祖父母/祖父母的信息。

我怎么能那样做?

fooID | fooName | barID | barName
- - - - - - - - - - - - - - - - -
1     |     One |     a | small_a  <-- This is the information I'm interested
1     |     One |     b | small_b  <-- Also this
2     |     Two |     c | small_c  <-- And this

编辑:fooIDfooName节点是祖祖父母的兄弟姐妹bar,包含Channel="High". barID和的情况几乎相同barName,它们是祖父母的兄弟姐妹,祖父母barClass包含Channel="High". 此外,我想要获得的是值1、和One,而不是通过它过滤,因为会有多个 foo 块。asmall_a

标签: python-3.xxmlxpath

解决方案


如果我理解正确,您可能正在寻找这样的东西(使用):

from lxml import etree
foos = """[your xml above]"""
items = []
for entry in doc.xpath('//foo[.//corgeReportRes[@Channel="High"]]'):
    items.append(entry.xpath('./fooID/text()')[0])
    items.append(entry.xpath('./fooName/text()')[0])
    items.append(entry.xpath('./bar/barID/text()')[0])
    items.append(entry.xpath('./bar/barName/text()')[0])
print('fooID | fooName | barID | barName')
print('  |  '.join(items))

输出:

fooID | fooName | barID | barName
1  |  One  |  a  |  small_a

推荐阅读