Python Lxml (objectify):检查标签是否存在

22 投票
4 回答
24449 浏览
提问于 2025-04-16 14:09

我需要检查一个xml文件里是否存在某个标签。

比如,我想看看这个片段里是否有这个标签:

 <main>
       <elem1/>
       <elem2>Hi</elem2>
       <elem3/>
       ...
 </main>

目前,我用了一种很笨的方法来检查错误,像这样:

try:
   if root.elem1.tag:
      foo = elem1
except AttributeError:
   foo = "error finding elem1"

如果找不到这个节点,我还想自定义一下提示信息(比如“找不到 -标签名-”)。

我需要检查一长串变量,不想把代码重复写100遍。

有什么建议吗?

编辑:

这是实际xml文件的一小部分:

<main>
 <asset name="Virtual Dvaered Unpresence">
  <virtual/>
  <presence>
   <faction>Dvaered</faction>
   <value>-1000.000000</value>
   <range>0</range>
  </presence>
 </asset>
 <asset name="Virtual Empire Small">
  <virtual/>
  <presence>
   <faction>Empire</faction>
   <value>100.000000</value>
   <range>2</range>
  </presence>
 </asset>
</main>

我想检查这个标签是否存在,如果存在的话,还想获取它的内容。

编辑编辑:好的,我打算把两个答案结合起来,但我只能投票给一个。抱歉。

编辑3:关于XPath的相关问题在这里: Python lxml (objectify): Xpath troubles

4 个回答

8

编辑: 更新了示例文件的答案。

我假设你是想在每个资产中搜索特定的标签。如果是这样的话,下面的代码对我来说是有效的:

import lxml.objectify

# Parse the file.
tree = lxml.objectify.parse('sample.xml')
root = tree.getroot()

# Which elements to find.
to_find = set(['presence/faction', 'presence/value', 'fake'])

# Go through each asset in the document.
for asset in root.findall('asset'):
    # Check for each element. 
    for name in to_find:
        node = asset.find(name)
        if node is not None:
            print 'Found %s, its value is %s' % (name, node)
        else:
            print 'Unable to find %s' % name

输出结果是:

Found presence/value, its value is -1000.0
Found presence/faction, its value is Dvaered
Unable to find fake
Found presence/value, its value is 100.0
Found presence/faction, its value is Empire
Unable to find fake
37

hasattr() 这个函数可以用来检查一个对象是否有某个属性。

if hasattr(root, 'elem1'):
    foo = root.elem1
7

假设你想获取elem2的值,你可以使用xpath来找到它。

tree = etree.parse(StringIO(htmlString), etree.HTMLParser()).getroot()
youWantValue = tree.xpath('/main/elem2')[0].text

撰写回答