4
<rules>
    <entry name="rule name 1">
      <to>
        <member>untrust</member>
      </to>
      <from>
        <member>trust</member>
      </from>
      <source>
        <member>object1</member>
      </source>
      <destination>
        <member>any</member>
      </destination>
      <service>any</service>
      <description>'NAT Rule 1'</description>
      <nat-type>ipv4</nat-type>
      <source-translation>
        <static-ip>
          <bi-directional>yes</bi-directional>
          <translated-address>object1-pub</translated-address>
        </static-ip>
      </source-translation>
    </entry>
    <entry name="rule name 2">
      <to>
        <member>untrust</member>
      </to>
      <from>
        <member>trust</member>
      </from>
      <source>
        <member>any</member>
      </source>
      <destination>
        <member>object2-pub</member>
      </destination>
      <destination-translation>
        <translated-address>object2</translated-address>
      </destination-translation>
      <service>any</service>
      <description>'NAT Rule 2'</description>
      <tag>
        <member>DST NAT</member>
      </tag>
    </entry>
</rules>    

Hi,

I am trying to process above xml using xml elementree in python. I am looking for a way to check if the <'source-traslation'> or <'destination-translation'> is present. In short, if it if source-translation then set nat-type varialble to source nat and proceed further to get and <'translated-address'> values. If <'destination-address'> is present then process logic to get values for . I am putting all this data in a dict with a format like this...

rules{
        rule_name: <name>
        options:{
                src_zone:<from>
                source:<source>
                dst_zone:<to>
                destination:<destination>
                nat-type:<appliaction>
                service:<service>
                traslated-address:<translated-address>
                destination-address:<destination-address>
        }       
}

I have tried various combinations however it is not working for me.

1 Answer 1

3

To check if your element exists you can have an if statement like this:

import xml.etree.ElementTree as ET
root = ET.parse('PATH_TO_YOUR_FILE').getroot()
if len(root.findall('source-translation')) > 0:
    PUT YOUR CODE HERE
Sign up to request clarification or add additional context in comments.

1 Comment

can root find subelement which is under child or do I need to loop it through the child node. In the final configuration, i will be parsing 300+ rule entry blocks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.