get attribute value using xmlstarlet or xmllint
Asked Answered
T

2

9

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?

Theretofore answered 3/2, 2018 at 8:3 Comment(1)
Duplicate of xmlstarlet select valueCupping
D
12

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
Disepalous answered 3/2, 2018 at 8:54 Comment(1)
OMG! That actually works. Even though I got it worked using awk, this should be accepted as correct answer because I was looking for a solution with xml-parser. Thanks!Theretofore
T
0

So I was able to get this done through awk.

awk '/ABC_enable/{print $4}' FS='"' xmlfile.xml

This works for me because "ABC_enable" will occur only once in this file and the format will remain same always. I understand this solution can't be generic but it gets my work done.

Theretofore answered 3/2, 2018 at 8:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.