XPath表达式有什么问题

时间:2016-06-21 19:41:38

标签: python xml xpath

对不起我是这个东西的新手。 我有这个(无法正确格式化我的代码所以我将它分成两个块):

<?xml version="1.0" encoding="UTF-8"?>
<bulkCmConfigDataFile xmlns:es="EricssonSpecificAttributes.14.04.xsd"
   xmlns:un="utranNrm.xsd" xmlns:xn="genericNrm.xsd"
   xmlns:gn="geranNrm.xsd" xmlns="configData.xsd">
   <fileHeader fileFormatVersion="32.615 V4.5" vendorName="Ericsson"/>
   <un:UtranCell id="U1">
      <un:attributes>
         <un:localCellId>1</un:localCellId>
         <un:uarfcnUl>9886</un:uarfcnUl>
         <un:uarfcnDl>10836</un:uarfcnDl>
         <un:primaryScramblingCode>335</un:primaryScramblingCode>
         <un:primaryCpichPower>300</un:primaryCpichPower>
         <un:maximumTransmissionPower>400</un:maximumTransmissionPower>
         <un:primarySchPower>-18</un:primarySchPower>
         <un:cId>1</un:cId>
         <un:userLabel>U_TST33_1</un:userLabel>
         <un:secondarySchPower>-35</un:secondarySchPower>
         <un:bchPower>-31</un:bchPower>
         <un:lac>65006</un:lac>
         <un:rac>6</un:rac>
         <un:sac>1</un:sac>
         <un:uraList>65006</un:uraList>
      </un:attributes>
   </un:UtranCell>
   <fileFooter dateTime="2016-04-13T15:11:31Z"/>
</bulkCmConfigDataFile>

我正在尝试

xpath_expr = "//{configData.xsd}bulkCmConfigDataFile/{utranNrm.xsd}UtranCell"
ucells = tree.xpath(xpath_expr)

但是得到了错误:

File "lxml.etree.pyx", line 2186, in lxml.etree._ElementTree.xpath (src\lxml\lxml.etree.c:60010)
File "xpath.pxi", line 359, in lxml.etree.XPathDocumentEvaluator.__call__ (src\lxml\lxml.etree.c:152734)
File "xpath.pxi", line 227, in lxml.etree._XPathEvaluatorBase._handle_result (src\lxml\lxml.etree.c:151097)
File "xpath.pxi", line 213, in lxml.etree._XPathEvaluatorBase._raise_eval_error (src\lxml\lxml.etree.c:150950)

lxml.etree.XPathEvalError:表达式无效

我在做什么有什么不对? 顺便说一下,执行这个

tree = etree.parse(infile)
root = tree.getroot()
print 'Root tag: ', root.tag
for child_of_root in root:
        print 'Child tags: ', child_of_root.tag, child_of_root.attrib

给出这个输出:

 - Root tag:  {configData.xsd}bulkCmConfigDataFile
 - Child tags:  {utranNrm.xsd}UtranCell {'id': 'U1'}

1 个答案:

答案 0 :(得分:0)

变量“root”的xml上下文已经位于&lt; bulkCmConfigDataFile&gt;节点,因此应该相对于此节点写入xpath。

例如

ucells = root.findall("un:UtranCell", namespaces={'un':'utranNrm.xsd'} )

ucells = root.findall("{utranNrm.xsd}UtranCell")

就个人而言,我更喜欢第一个选项,因为命名空间可以定义一次,最终使xpath更具可读性。

这将返回一个元素列表,然后您可以使用

进行迭代
 for cell in ucells:
     print cell.get('id')

或者,如果您知道只有1个UtranCell,请使用root.find()返回单个元素。