Mac|CentOS使用shell指令解析XML

xmllint (系统自带的指令)

 如果您输入的XML包含前缀的名称空间,则必须使用local-name()代替name()。
CentOS
  • 使用--xpath的时候会有问题,可以选择--shell
#  xmllint --xpath "/" pom.xml 
Unknown option --xpath
Usage : xmllint [options] XMLfiles ...
    Parse the XML files and output the result of the parsing
    --version : display the version of the XML library used
    --debug : dump a debug tree of the in-memory document
......
  • 使用--shell(CentOS和MacOS通用)
# xmllint --shell pom.xml 
/ > xpath //*[name() = 'project']/*[name() = 'version']/text()
Object is a Node Set :
Set contains 1 nodes:
1  TEXT
    content=1.1.5-SNAPSHOT
/ >
Mac
  • 使用--xpath(在CentOS6.5中,由于libxml2的版本过低,所以无法直接使用--xpath)
okami$ xmllint --xpath "//*[name() = 'project']/*[name() = 'version']/text()" pom.xml
1.1.5-SNAPSHOT
  • 使用--shell
okami$ xmllint --shell pom.xml 
/ > xpath //*[name() = 'project']/*[name() = 'version']/text()
Object is a Node Set :
Set contains 1 nodes:
1  TEXT
    content=1.1.5-SNAPSHOT
/ >

xpath

xpath目前只发现可以在MacOS上使用,CentOS上暂时没有找到该工具
  • MacOS
okami$ xpath pom.xml "/project/version/text()"
Found 1 nodes:
-- NODE --
1.1.5-SNAPSHOT

xml2

  • MacOs和CentOS的用法都一样
okami$ cat pom.xml |xml2 |grep /project/version
/project/version=1.1.5-SNAPSHOT

xmlstarlet

安装 xmlstarlet

  • CentOS
# yum install xmlstarlet -y
  • MacOS
okami$ brew install xmlstarlet
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 2 taps (homebrew/core and homebrew/cask).
==> Updated Formulae
bit             exploitdb       go@1.12         minikube        navi            pandoc          stress-ng       terrahub        unbound         wxmaxima
convox          gnome-autoar    mesa            msgpack         paket           powerline-go    sysbench        traefik         unrar

==> Downloading https://homebrew.bintray.com/bottles/xmlstarlet-1.6.1.mojave.bottle.tar.gz
######################################################################## 100.0%
==> Pouring xmlstarlet-1.6.1.mojave.bottle.tar.gz
🍺  /usr/local/Cellar/xmlstarlet/1.6.1: 15 files, 193.2KB

使用 xmlstarlet

# xmlstarlet sel -t -v  "//*[name() = 'project']/*[name() = 'version']/text()" pom.xml
1.0-SNAPSHOT

参考链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。