How to select all XML nodes that have a given child in Python 3?

30 views Asked by At

I have the following XML from nmap:

<nmaprun>
    <host>
        <address>
        <hostsnames>
        <ports>
        <hostscript>
    </host>
    <host>
        <address>
        <hostsnames>
        <ports>
    </host>
    <host>
        <address>
        <hostsnames>
        <ports>
        <hostscript>
    </host>
</nmaprun>

I only want to get the host elements that have the child hostscript. I followed the Python 3 tutorial with root.findall(".//hostscript/..[@name='host']"). In the example above, I should get only 2 out of 3.

1

There are 1 answers

1
Gordon On BEST ANSWER

To select the host elements that have the child hostscript, you can use this XPath:

/nmaprun/host[hostscript]

As others pointed out in the comments to your question, @name is looking for an attribute node. You likely wanted to use name() instead.