Pregunta

Considering the code example below,

if 'xpath' in request.args:
    in = request.args['xpath']
    xml = BytesIO(open("/file.xml").read())
    for v, e in etree.iterparse(xml):
         return e.text

the following XML file,

<a>
   <c>
      <d>content X</d>
   </c>
   <c>
      <d>content Y</d>
   </c>
</a>

and that the in variable receives the string /a/c[2]/d with curl, as bellow

curl http://localhost:5000/home?xpath=/a/c[2]/d

is there any way that from the given string (xpath expression) the code returns the element text (i.e. is able to understand which element I'm referring to)?

¿Fue útil?

Solución

To return the element located by in, you can call the find method on the parsed ElementTree.

return etree.parse(xml).find(in).text

Note that the XPath expression must not include the root element itself, nor a starting slash, so c[2]/d should do the trick.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top