Extract value from xml file with namespaces by usi

2019-05-26 03:06发布

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.

2条回答
2楼-- · 2019-05-26 03:15

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
查看更多
beautiful°
3楼-- · 2019-05-26 03:35

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]
查看更多
登录 后发表回答