【问题标题】:ElementTree parsing in pythonPython中的ElementTree解析
【发布时间】:2013-03-28 09:36:10
【问题描述】:

我有表单的 xml

<root>
  <tag1>   </tag1>
  <tag2>   </tag2>
  <tag3>   </tag3>

  <tag1>   </tag1>
  <tag2>   </tag2>
  <tag3>   </tag3>
</root>

我需要按顺序解析xml

tag1 -> tag2 -> tag3 -> tag1 -> tag2 -> tag3 

目前我正在使用

root = tree.getroot()
for data in root.findall('tag1')
    do_operations(data)
for data in root.findall('tag2')
    do_operations(data)

但是这种方法给了我,这很明显

tag1 -> tag1 -> tag2 -> tag2 -> tag3 -> tag3

这不是我想要的。

您能否建议一种最佳方法,使我可以以所需的方式传递 XML。 tag1 , tag2 , tag3 以与上面给出的相同顺序重复很多。

【问题讨论】:

  • 您使用的是什么模块/库??
  • @Schoolboy ElementTree?

标签: python parsing elementtree


【解决方案1】:

IIUC,你不能简单地循环 root 本身吗?

>>> for data in root:
...     print data
...     
<Element tag1 at 0x102dea7d0>
<Element tag2 at 0x102dea8c0>
<Element tag3 at 0x102dd6d20>
<Element tag1 at 0x102dea7d0>
<Element tag2 at 0x102dea8c0>
<Element tag3 at 0x102dd6d20>

【讨论】:

  • @Abhishek:这些只是id() 结果的十六进制版本,作为区分同名标签与__repr__ 的一种方式。
  • 如果我让它们在 XML 中重复 100 次怎么办。我不能用这种方式写它们
  • @Abhishek:我不明白。那些不是我写的,那些是print data的结果。不用for data in root.findall('tag1'):,直接用for data in root:,才是重点。
  • 好的,现在知道了。我认为它们必须在程序中进行硬编码。明白你的意思。
【解决方案2】:

你可以遍历子元素而不是使用 find:

for child in root:
    do operations...

如果对不同的标签做不同的操作,可以通过child.tag来判断:

for child in root:
    if child.tag == 'tag1':
       do operations
    elif child.tag == 'tag2':
       do other operations
    ...

或者您可以将操作放在一个 dict 中并避免使用 if-elif-else 咒语。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多