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

一世执手 提交于 2020-01-02 19:10:33

问题


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.


回答1:


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



回答2:


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]


来源:https://stackoverflow.com/questions/43694722/extract-value-from-xml-file-with-namespaces-by-using-xmllint-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!