簡體   English   中英

Python Lxml(objectify):檢查標簽是否存在

[英]Python Lxml (objectify): Checking whether a tag exists

我需要檢查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麻煩

hasattr()適用於此:

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

編輯 :樣本文件的更新答案。

我假設你想搜索每個資產的某些標簽。 如果是這樣,以下內容對我有用:

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

假設您想獲得elem2的值,您可以使用xpath來查找它。

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

如果您的文檔往往相對較短,您可以遍歷<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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM