0

I am using xml.etree in python to generate an xml document, now while I am generating the xml document I want to get the xpath of a element that I have created, is there anyway of getting the absolute path while still creating the Element?

Below is an example of the generation process:

ParameterDeclaration = Element("ParameterDeclarations")
Parameter = Element("ParameterDeclaration")
Parameter.set("name", "Speed")
Parameter.set("value", action.speed)
Parameter.set("parameterType", "double")
ParameterDeclaration.append(Parameter)

Can I get the path of the Parameter element right after that last line?

Please note that this is only a small section of the xml file, the ParameterDeclaration is being appended to another element.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
gjossep
  • 23
  • 5
  • Can't you use xpath element .. to explore and print your ancestors starting with ./.. and working back to root? – David G. Pickett Jun 11 '20 at 16:30
  • Im not sure what you mean? – gjossep Jun 11 '20 at 19:27
  • lxml has a `getpath()` method. Would that help? https://stackoverflow.com/a/1577495/407615 – mzjn Jun 12 '20 at 08:00
  • That only works on an ElementTree not Element itself. Im quite new to the whole xml thing, but thanks – gjossep Jun 12 '20 at 10:10
  • `getpath` is a ElementTree method and it returns the path of an Element. – mzjn Jun 12 '20 at 10:14
  • Thanks! I now get it telling me that ElementTree does not have a method called getpath()? Any idea AttributeError: 'ElementTree' object has no attribute 'getPath' – gjossep Jun 12 '20 at 11:35
  • Did you install lxml? https://lxml.de/installation.html – mzjn Jun 12 '20 at 12:28
  • I wrote something like that for my JAVA FIXML tree parser, my path is /my_name prefixed by my parent's path, unless I am root (null parent), so the call in my element object crawled up the tree adding prefixes recursively until it hit root and returned the string all the way back, great for debugging. So, if you can access your parent by xpath .., you can walk up the tree to rool accumulating names between slashes in a string. – David G. Pickett Jun 12 '20 at 21:14

0 Answers0