Help with ElementTree

Peter Otten __peter__ at web.de
Thu Apr 9 14:39:02 EDT 2015


Larry Martell wrote:

> I have an XML file that looks like this (this is just the pertinent
> part, the file is huge):
> 
> <?xml version="1.0"?>
> <Root>
>   <Doc Type="CCI">
>     <Node Name="SystemConfig" Section="yes">
>         <Node Name="Environment">
>            <Parameter Name="ToolName">
>               <Value>
>                  <Default>KA21</Default>
>                  <Current>KA21</Current>
>              </Value>
>            </Parameter>
>          </Node>
>       </Node>
> 
>     <Node Name="Events" Section="yes">
>        <Parameter Name="LastEventExportTime">
>          <Value>
>            <Default>00:00:00</Default>
>            <Current>15/03/2014 05:56:00</Current>
>          </Value>
>        </Parameter>
>     </Node>
>   </Doc>
> </Root>
> 
> I would like to use ElementTree to get 2 values from this:
> 
> SystemConfig.Environment.ToolName.Current
> Events.LastEventExportTime.Current
> 
> I've been trying for hours to get ElementTree to give me these 2
> values, but nothing I do seems to work. Can anyone help me with this?

Try it in the interactive interpreter, one step after another:

>>> from xml.etree import ElementTree
>>> root = ElementTree.fromstring("""<?xml version="1.0"?>
... <Root>
<snip>
... </Root>
... """)
>>> root.find("Doc")
<Element 'Doc' at 0x7f12af916098>
>>> root.find("Doc/Node")
<Element 'Node' at 0x7f12af9218b8>
>>> root.find("Doc/Node/Node/Parameter/Value/Current").text
'KA21'

That "worked" because the Node elements involved are the first in the 
document. You may have to add more "conditions" until there is no ambiguity 
left, e. g. to pick the child node of Doc with the Name="Events" attribute:

>>> root.find("Doc/Node[@Name='Events']/Parameter/Value/Current").text
'15/03/2014 05:56:00'

See 

https://docs.python.org/dev/library/xml.etree.elementtree.html#xpath-support

for the details.




More information about the Python-list mailing list