lxml

2011-05-25 14 views
27

से विशेषता मानों का चयन करना मैं एक विशेषता का मान प्राप्त करने के लिए xpath अभिव्यक्ति का उपयोग करना चाहता हूं।lxml

Traceback (most recent call last): 
    File "bob.py", line 22, in <module> 
    print customer.find('./@ID') 
    File "lxml.etree.pyx", line 1409, in lxml.etree._Element.find (src/lxml/lxml.etree.c:39972) 
    File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 272, in find 
    it = iterfind(elem, path, namespaces) 
    File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 262, in iterfind 
    selector = _build_path_iterator(path, namespaces) 
    File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 246, in _build_path_iterator 
    selector.append(ops[token[0]](_next, token)) 
KeyError: '@' 

मैं गलत हूँ इस काम करने की उम्मीद करने के लिए:

मैं

from lxml import etree 

for customer in etree.parse('file.xml').getroot().findall('BOB'): 
    print customer.find('./@NAME') 

काम करने के लिए निम्नलिखित लेकिन यह एक त्रुटि देता है की उम्मीद?

उत्तर

37

find और findallonly implement a subset XPath के। उनकी उपस्थिति अन्य एलिमेंट ट्री कार्यान्वयन (जैसे ElementTree और cElementTree) के साथ संगतता प्रदान करने के लिए है।

xpath विधि, इसके विपरीत, XPath 1.0 के लिए पूर्ण पहुँच प्रदान करता है:

print customer.get('NAME') 

या attrib:

print customer.attrib['NAME'] 
+6

सही

print customer.xpath('./@NAME')[0] 

हालांकि, अगर आप के बजाय get इस्तेमाल कर सकते हैं , लेकिन यदि आप "आधिकारिक तौर पर" पसंदीदा तरीका चाहते हैं: 'customer.get ('NAME' का उपयोग करें ')' (http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.attrib देखें) – Steven

संबंधित मुद्दे