0
我正在處理一些共享自定義名稱空間的XML文檔。我有各種各樣的具有相同名稱空間的文件,並試圖找出解析時處理名稱空間的最佳/最優雅的方式。下面是一個示例:在lxml解析函數中處理全局名稱空間
在特定腳本的開頭,我讀取了一個XML文件,使用etree.parse()
解析它,檢查第一個或兩個標記來標識命名空間,然後將它們保存在某處。我可以把它們放在全球範圍內,但現在它們被儲存在班級self.ns
。
我有這個函數,我寫了從給定的xpath查詢返回值。它看起來像這樣:
# noinspection PyBroadException
def get_value(self, lxml_object, xpath_query=None, return_int=False):
"""
BE CAREFUL using this function because it will catch all xpath query exceptions
:param lxml_object: an lxml.etree object
:param xpath_query: a valid xpath query
:param return_int: set to True if you want an int rather than a string
:return: the value of the field corresponding to the xpath query
"""
if return_int is True:
if xpath_query:
try:
return int(lxml_object.xpath(xpath_query, namespaces=self.ns)[0].text)
except:
return None
else:
try:
return int(lxml_object[0].text)
except:
return None
else:
if xpath_query:
try:
return lxml_object.xpath(xpath_query, namespaces=self.ns)[0].text
except:
return None
else:
try:
return lxml_object[0].text
except:
return None
這是好的,當我把它放在我的類中並調用self.get_value()
因爲self.ns
已定義。
我在很多不同的腳本中使用這個函數,並希望把它放在一個單獨的文件中解析實用程序,我可以從中導入它。然而,這引起了添加命名空間參數,併爲每一個我用它的時候的命名空間傳遞給函數的幽靈,像
return get_value(some_lxml_object, 'some xpath query', ns=self.ns)
我怎樣組織這一切,如果我不想每次我調用函數時都必須傳遞一個名稱空間參數?