Python XML Grab IP from File Between CDATA
Question: I have an XML dump file that I want to parse for the first occurrence of
'ETH0_IP'. However, the cdata field is throwing me. It ends up returning
'None'. There are other IPs that appear further in the file but I don't care
about those.

I have something like this so far:

    
    
      q = etree.parse(outputfile)
      fileoutputip = q.findtext("ETH0_IP")
    

This is the XML:

    
    
    <VM>
      <ID>####</ID>
      <UID>0</UID>
      <GID>0</GID>
      <UNAME>####</UNAME>
      <GNAME>###</GNAME>
      <NAME>###</NAME>
      <PERMISSIONS>
        <OWNER_U>1</OWNER_U>
        <OWNER_M>1</OWNER_M>
        <OWNER_A>0</OWNER_A>
        <GROUP_U>0</GROUP_U>
        <GROUP_M>0</GROUP_M>
        <GROUP_A>0</GROUP_A>
        <OTHER_U>0</OTHER_U>
        <OTHER_M>0</OTHER_M>
        <OTHER_A>0</OTHER_A>
      </PERMISSIONS>
      <LAST_POLL>1461191030</LAST_POLL>
      <STATE>3</STATE>
      <LCM_STATE>3</LCM_STATE>
      <PREV_STATE>3</PREV_STATE>
      <PREV_LCM_STATE>3</PREV_LCM_STATE>
      <RESCHED>0</RESCHED>
      <STIME>1461189864</STIME>
      <ETIME>0</ETIME>
      <DEPLOY_ID>###</DEPLOY_ID>
      <MEMORY>###</MEMORY>
      <CPU>0</CPU>
      <NET_TX>1000</NET_TX>
      <NET_RX>73254</NET_RX>
      <TEMPLATE>
        <AUTOMATIC_REQUIREMENTS><![CDATA[!(PUBLIC_CLOUD = YES)]]></AUTOMATIC_REQUIREMENTS>
        <CONTEXT>
          <DISK_ID><![CDATA[1]]></DISK_ID>
          <ETH0_DNS><![CDATA[####]]></ETH0_DNS>
          <ETH0_GATEWAY><![CDATA[###]]></ETH0_GATEWAY>
          <ETH0_IP><![CDATA[10.**.***.**]]></ETH0_IP>
    


Answer: `q.findtext("ETH0_IP")` would try to find `ETH0_IP` element _directly under
the root element in the tree_ and in this case it results into `None` since
`VM` does not have a direct `ETH0_IP` child.

You can solve it by providing the XPath expression (to look for the `ETH0_IP`
element anywhere in the tree) to `find()` or `findtext()`, or by using
`xpath()` method directly:

    
    
    >>> from lxml import etree
    >>> 
    >>> tree = etree.parse("input.xml")
    >>> print(tree.find(".//ETH0_IP").text)
    10.**.***.**
    >>> print(tree.findtext(".//ETH0_IP"))
    10.**.***.**
    >>> print(tree.xpath("//ETH0_IP")[0].text)
    10.**.***.**
    

