E Bobrov E Bobrov - 5 months ago 28
Python Question

What is wrong with XPath expression

Sorry I`m new for this stuff.
I have this (was unable to format my code properly so I splitted it in two blocks bellow):

<?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>


I`m trying to do

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


But get en error:

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: Invalid expression

What's wrong with what I am doing?
By the way, executing this

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


Gives this output:

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

Answer

Change

xpath_expr = "//{configData.xsd}bulkCmConfigDataFile/{utranNrm.xsd}UtranCell"

to

xpath_expr = "//bulkCmConfigDataFile/un:UtranCell"
ucells = tree.XPath(xpath_expr, namespaces={'un':'utranNrm.xsd'} )

For xpath, you need to use the namespace prefixes so

bulkCmConfigDataFile does not need a namespace prefix because it is the default (i.e. xmlns=....) and, UtranCell uses a prefix of "un:" (i.e. xmlns:un= ....)