Search code examples
xmlawksedxmlstarletxmllint

get attribute value using xmlstarlet or xmllint


I have gone through several of questions since last two days but yet to find a solution. Here is my xml:

<?xml version="1.0" encoding="UTF-8"?>

<Environment xmlns="http://schemas.dmtf.org/ovf/environment/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oe="http://schemas.dmtf.org/ovf/environment/1" xmlns:ve="http://www.vmware.com/schema/ovfenv" oe:id="" ve:vCenterId="">
   <PropertySection>
     <Property oe:key="vami.hostname" oe:value="jal"/>
     <Property oe:key="vamitimezone" oe:value="Asia/Kolkata"/>
     <Property oe:key="ABC_enable" oe:value="1"/>
     <Property oe:key="software_only_installer_name" oe:value="install-r8-0-0-0"/>
     <Property oe:key="software_only_staging_dir" oe:value="/media/dir"/>
     <Property oe:key="software_only_mount_dir" oe:value="/media/cdrom"/>
  </PropertySection>
</Environment>

I want to get attribute value(oe:value) when oe:key="ABC_enable".

I have tried many times with xmllint and xmlstarlet but couldn't get what I want. Can you please help?


Solution

  • The right way with xmlstarlet tool:

    Input:

    xmlstarlet select \
        -N oe="http://schemas.dmtf.org/ovf/environment/1" \
        -N ve="http://www.vmware.com/schema/ovfenv" \
        --net \
        -t -v '//oe:Property[@oe:key="ABC_enable"]/@oe:value' \
        -n input.xml
    

    Output:

    1