Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract value from xml file with namespaces by using xmllint in bash

I need to extract the name value (Product Finder) from this xml:

File: config.xml

<?xml version="1.0" encoding="utf-8"?>
<widget id="com.abc.app" version="1.3.1" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0" ios-CFBundleVersion="1.3.1.5" android-versionCode="5">
    <name>Product Finder</name>
    <description>
        Description
    </description>
</widget>

I've tried:

mles$ xmllint --xpath "/widget/name/text()" config.xml 
XPath set is empty

Which is probably because my config.xml file has other namespaces. According to this question I need to set the namespace by hand. So I've tried:

mles$ xmllint --shell config.xml / > setns x=http://www.w3.org/ns/widgets / > xpath /x:widget/name/text

There is no output on this one. Whats the correct syntax to extract the name value with xmllint?

Note: I already have a solution with grep and sed, but I would like to use xmllint.

like image 302
mles Avatar asked Oct 15 '25 19:10

mles


2 Answers

Your file uses namespaces (xmlns). To be independent of these, I suggest:

xmllint --xpath "//*[local-name()='widget']/*[local-name()='name']/text()" config.xml

Output:

Product Finder
like image 174
Cyrus Avatar answered Oct 18 '25 13:10

Cyrus


Notice that not only the element where the default namespace is declared resides in that namespace, but all descendant elements without prefix and without local default namespace implicitly inherit the default namespace from the ancestor. This means you also need to use the prefix x to reference name element since it inherits the default namespace from widget :

/ > xpath /x:widget/x:name/text()[1]
like image 28
har07 Avatar answered Oct 18 '25 13:10

har07