Ken J
Ken J

Reputation: 4562

XPath Query by Child Attribute

I have a very large XML file that I need to extract specific info from. I need to grab all of the node attributes that have associated child elements. Here's an example of how the elements are laid out:

<key name="Test Group">
   <key name="Exhibit A">
      <key name="Chicago">
        <key name="server-01-chi">
          <dword name="[SSH2] Port">22</dword>
       </key>
       <key name="server-02-chi">
         <dword name="[SSH2] Port">22</dword>
       </key>
     </key>
  </key>
   <key name="Exhibit B">
      <key name="Denver">
        <key name="server-01-den">
          <dword name="[SSH2] Port">22</dword>
       </key>
       <key name="server-02-den">
         <dword name="[SSH2] Port">22</dword>
       </key>
     </key>
  </key>           
</key>

In this case I want to grab the server names which are node attributes. So given the above XML I need this output:

server-01-chi
server-02-chi
server-01-den
server-02-den

Upvotes: 2

Views: 517

Answers (1)

alecxe
alecxe

Reputation: 473763

One option would be to retrieve all key elements having dword direct child:

//key[dword]/@name

Or, get key elements that have name attribute starting with "server":

//key[starts-with(@name, "server")]/@name

Or, go through all the key parents as well (if the structure is "strict"). For example, if the name of test test group is known beforehand:

//key[@name = 'Test Group']/key/key/key/@name

All the expressions work for me on the provided sample XML matching the server names.

Upvotes: 4

Related Questions