21

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

例如,我想查看此代码段中是否存在标记:

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

目前,我正在使用带有错误检查的丑陋黑客,如下所示:

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

如果找不到节点(即“无法找到-tagname-”),我还想自定义字符串。

我必须检查一长串变量,而且我不想重复代码 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

4 回答 4

36

hasattr()为此工作:

if hasattr(root, 'elem1'):
    foo = root.elem1
于 2012-01-09T09:08:02.787 回答
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
于 2011-03-22T02:03:35.240 回答
7

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

tree = etree.parse(StringIO(htmlString), etree.HTMLParser()).getroot()
youWantValue = tree.xpath('/main/elem2')[0].text
于 2011-03-22T04:17:47.833 回答
2

如果您的文档往往相对较短,您可以遍历所有子项以<main>查找与您的变量名称集匹配的标签:

tree = lxml.etree.fromstring(DATA)
NAMES = set(['elem1', 'elem3'])
for node in tree.iterchildren():
    if node.tag in NAMES:
        print 'found', node.tag

或者您可以一次搜索每个变量名称:

for tag in ('elem1', 'elem3'):
    if tree.find(tag) is not None:
        print 'found', tag
于 2011-03-22T01:51:44.683 回答