打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
XMLStarlet 使用入门

在 IBM Bluemix 云平台上开发并部署您的下一个应用。

开始您的试用

XMLStarlet 是一种开放源码的 XML 工具箱,可以在 UNIX?、Mac OS? X 或 Microsoft? Windows? 命令行中使用。XMLStarlet 可以验证 XML、格式化 XML、选择其中的一部分、用 XSLT 进行转换甚至编辑。这意味着,不需要使用 Perl 或 Java? 之类的编程语言编写任何自定义的代码,就可以在 shell 脚本中加入 XML 工具。

使用 XMLStarlet 需要安装它,而安装需要 libxml2 和 libxslt2 库。在 Windows 上不需要安装 libxml2 和 libxslt2,因为 Win32 包已经包含了。可以下载 Win32 可执行文件并将其安装到方便从命令行执行的任何位置。如果运行 UNIX,而机器上还没有 libxml2 和 libxslt2,则必须下载并安装(请参阅 参考资料)。

然后转到 XMLStarlet 主页下载最新的构建包(请参阅 参考资料)。运行 ./configure 脚本以便设置构建脚本,然后运行 make install 构建包并安装。如果您不是超级用户,应该使用 sudo make install 以便将命令安装到 system 目录中。

可能还需要访问 XML、XSLT 和 XML Path Language (XPath) 页面以便及时更新这三个标准,这对于充分利用 XMLStarlet 非常重要(请参阅 参考资料)。

基础

安装完成后,现在可以对 XMLStarlet 做一番漫游了。首先不带参数运行 xml 命令(参见清单 1)。

清单 1. XMLStarlet 帮助页
% xml
XMLStarlet Toolkit: command-line utilities for XML
Usage: xml [<options>] <command> [<cmd-options>]
where <command> is one of:
ed    (or edit)      - Edit/Update XML document(s)
sel   (or select)    - Select data or query XML document(s) (XPATH, etc)
tr    (or transform) - Transform XML document(s) using XSLT
val   (or validate)  - Validate XML document(s) (well-formed/DTD/XSD/RelaxNG)
fo    (or format)    - Format XML document(s)
el    (or elements)  - Display element structure of XML document
c14n  (or canonic)   - XML canonicalization
ls    (or list)      - List directory as XML
esc   (or escape)    - Escape special XML characters
unesc (or unescape)  - Unescape special XML characters
pyx   (or xmln)      - Convert XML into PYX format (based on ESIS - ISO 8879)
p2x   (or depyx)     - Convert PYX into XML
<options> are:
--version            - show version
--help  - show help
Wherever file name mentioned in command help it is assumed
that URL can be used instead as well.
Type: xml <command> --help <ENTER> for command help
XMLStarlet is a command line toolkit to query/edit/check/transform
XML documents (for more information see http://xmlstar.sourceforge.net/)

所有命令的基本格式为 xml <command>,后面跟一些选项。了解每个选项可以使用 xml <command> --help 命令。比如,清单 2 显示了编辑(ed)命令的帮助。

清单 2. 编辑命令的帮助
% xml ed --help
XMLStarlet Toolkit: Edit XML document(s)
Usage: xml ed <global-options> {<action>} [ <xml-file-or-uri> ... ]
where
<global-options>  - global options for editing
<xml-file-or-uri> - input XML document file name/uri (stdin otherwise)
<global-options> are:
-P (or --pf)        - preserve original formatting
-S (or --ps)        - preserve non-significant spaces
-O (or --omit-decl) - omit XML declaration (<?xml ...?>)
-N <name>=<value>   - predefine namespaces (name without 'xmlns:')
ex: xsql=urn:oracle-xsql
Multiple -N options are allowed.
-N options must be last global options.
--help or -h        - display help
where <action>
-d or --delete <xpath>
-i or --insert <xpath> -t (--type) elem|text|attr -n <name> -v (--value) <value>
-a or --append <xpath> -t (--type) elem|text|attr -n <name> -v (--value) <value>
-s or --subnode <xpath> -t (--type) elem|text|attr -n <name> -v (--value) <value>
-m or --move <xpath1> <xpath2>
-r or --rename <xpath1> -v <new-name>
-u or --update <xpath> -v (--value) <value>
-x (--expr) <xpath> (-x is not implemented yet)
XMLStarlet is a command line toolkit to query/edit/check/transform
XML documents (for more information see http://xmlstar.sourceforge.net/)

这份帮助文件看起来很复杂,但最重要的部分在下面,可以看到如何删除、插入 XML 节点或者改变节点的值,等等。

长代码行

本文中的一些代码行很长,如果不断开就无法在窗口中显示出来。这些行在代码清单中被折叠起来,虽然在实际的命令行中只有一行。这些行用 ? 符号表示(比如清单 3)。

回页首

XML 目录列表

使用 XMLStarlet 需要有 XML,因此我们介绍第一个命令 xml ls,它用 XML 给出当前目录的列表。清单 3 给出了一个例子。

清单 3. XML 目录列表
% xml ls
<xml>
    <d p="rwxr-xr-x" a="2005.05.04 23:03:46" 
    ? m="2004.03.24 16:21:02" s="374" n="."/>
    <d p="rwxr-xr-x" a="2005.05.04 23:03:46" 
    ? m="2005.05.04 22:13:41" s="1938"n=".."/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.24 01:13:43" s="6148"n=".DS_Store"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.24 00:41:46" s="173" n="build.xml"/>
    <d p="rwxr-xr-x" a="2005.04.30 11:34:27" 
    ? m="2004.03.24 01:13:43" s="544" n="docs"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.21 18:41:58" s="641" n="input.xml"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.23 23:41:15" s="3587"n="main.xsl"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.24 00:37:10" s="184" n="Makefile"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.24 00:36:41" s="3869"n="MyGenerator.class"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.24 00:36:33" s="5265"n="MyGenerator.java"/>
    <d p="rwxr-xr-x" a="2005.04.30 11:34:25" 
    ? m="2004.03.24 00:20:07" s="272" n="output"/>
</xml>

如果认为目录列表显示的信息太多了,可以(比方说)去掉目录节点,如清单 4 所示。

清单 4. 不含目录节点的列表
% xml ls | xml ed -d "//d"
<?xml version="1.0"?>
<xml>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.24 01:13:43" s="6148" n=".DS_Store"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.24 00:41:46" s="173" n="build.xml"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.21 18:41:58" s="641" n="input.xml"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.23 23:41:15" s="3587" n="main.xsl"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.24 00:37:10" s="184" n="Makefile"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.24 00:36:41" s="3869" n="MyGenerator.class"/>
    <f p="rw-r--r--" a="2005.03.24 17:53:52" 
    ? m="2004.03.24 00:36:33" s="5265" n="MyGenerator.java"/>
</xml>

使用编辑命令(ed)从 XML 中去掉了 d 节点。ls 命令把目录输出到标准输出。管道符(|)将标准输出重定向到编辑命令的标准输入,编辑命令从列表中删除 d 节点。使用 XPath 表达式 //d 指定 d 节点,它和树中所有层次上的 d 节点匹配。如果要更加准确,可以使用 /xml/d

现在,假设要删除 am 属性(如清单 5 所示)。

清单 5. 删除 a 和 m 属性的目录列表
% xml ls | xml ed -d "//d" -d "//@a" -d "//@m" -d "//@p"
<?xml version="1.0"?>
<xml>
    <f s="6148" n=".DS_Store"/>
    <f s="173" n="build.xml"/>
    <f s="641" n="input.xml"/>
    <f s="3587" n="main.xsl"/>
    <f s="184" n="Makefile"/>
    <f s="3869" n="MyGenerator.class"/>
    <f s="5265" n="MyGenerator.java"/>
</xml>

现在更简洁了,清单中只剩下了文件,文件节点中只能看到文件的大小和名称。为了更便于跟踪,可以将结果保存在一个名为 ls.xml 的文件中。也可使用 rename 编辑函数将 f 标签修改为 file(如清单 6 所示)。

清单 6. 显示大小和文件名属性的目录列表
% cat ls.xml | xml ed -r "//f" -v "file"
<?xml version="1.0"?>
<xml>
    <file s="6148" n=".DS_Store"/>
    <file s="173" n="build.xml"/>
    <file s="641" n="input.xml"/>
    <file s="3587" n="main.xsl"/>
    <file s="184" n="Makefile"/>
    <file s="3869" n="MyGenerator.class"/>
    <file s="5265" n="MyGenerator.java"/>
</xml>

此外,如果标签和属性不愿意使用短名字如 sn,可以分别将其修改为 sizename(如图 7 所示)。

清单 7. 使用 file 标签的目录列表
% cat ls.xml | xml ed -r "//f" -v "file" -r "//@s" -v "size" -r "//@n" -v "name"
<?xml version="1.0"?>
<xml>
    <file size="6148" name=".DS_Store"/>
    <file size="173" name="build.xml"/>
    <file size="641" name="input.xml"/>
    <file size="3587" name="main.xsl"/>
    <file size="184" name="Makefile"/>
    <file size="3869" name="MyGenerator.class"/>
    <file size="5265" name="MyGenerator.java"/>
</xml>

这样读起来更容易了。到现在还没有写一行 XSLT、Perl 或 Java 代码。将该文件保存为 ls2.xml。

回页首

验证

新的目录列表看起来不错,那么是不是仍然有效呢?清单 8 说明了如何来进行判断。

清单 8. 检查 XML 的良构性
% xml val ls2.xml
ls2.xml - valid

啊,是有效的。就是说它是结构良好的,即标签是平衡的、字符编码是正确的等等。但是仍然可能缺少必要的标签或者正确的标签。为此必须知道文件的正确结构,因此需要一个模式。只有用模式检查 XML 文档并且通过之后才能说它是有效的。

清单 9 显示了 XML 目录列表文件的基本 RELAX NG 模式。

清单 9. RELAX NG 模式
<?xml version="1.0" encoding="UTF-8"?>
<grammar ns="" xmlns=http://relaxng.org/ns/structure/1.0
datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
  <start>
    <element name="xml">
      <oneOrMore>
        <element name="file">
          <attribute name="name">
            <data type="NMTOKEN"/>
          </attribute>
          <attribute name="size">
            <data type="integer"/>
          </attribute>
        </element>
      </oneOrMore>
    </element>
  </start>
</grammar>

RELAX NG 读起来很容易。最上面的 element 标签定义了 xml 作为基本标签。然后,xml 标签中的 oneOrMore 标签被命名为 filesize

ls2.xml 文件对于这个新的模式有效吗?请参阅清单 10。

清单 10. 用模式检查
% xml val -e -r ls.rng ls2.xml
ls2.xml - valid

如果您像我一样 —— 只有看到错误才会满足,那么可以在 ls3.xml 文件中的一个文件节点中添加属性 someAttribute,然后再检查该文件(参见清单 11)。

清单 11. 用模式检查错误的文件
% xml val -e -r ls.rng ls3.xml
ls3.xml:4: element file: Relax-NG validity error : 
? Invalid attribute someAttribute for element file
ls3.xml - invalid

结果证明失败了。不但要知道文件是结构良好的,还要知道所有的标签和属性都是正确的。

回页首

文本

还可以使用选择函数从 XML 提取数据元素。清单 12 中的例子从 XML 目录中提取文件名作为普通文本。

清单 12. 提取文件名
% xml sel -t -m "/xml/file" -v "concat(@name,'
')" ls2.xml
.DS_Store
build.xml
input.xml
main.xsl
Makefile
MyGenerator.class
MyGenerator.java

这里要注意两点。首先,提取文件名的 XPath 是 /xml/file 条款。其次使用 -v 选项的输出说名用回车换行连接 file 标签中的 name 属性。

现在增加 -s 选项,按照 size 属性对文件排序(参见清单 13)。 A:N:- 语法告诉 XMLStarlet 按照数值大小递增排序。(这里将 size 参数添加到 concat 语句中以便能正常工作。)

清单 13. 列表排序
% xml sel -t -m "/xml/file" -s A:N:- "@size" -v "concat 
? ( @name,':',@size,'
' ) " ls2.xml
build.xml:173
Makefile:184
input.xml:641
main.xsl:3587
MyGenerator.class:3869
MyGenerator.java:5265
.DS_Store:6148

回页首

牛刀小试

为了让 xml 命令做点实际工作,可以使用它解析一份交通报告。 Yahoo!? Maps 提供了交通服务,可以使用 curl 命令和 -g 选项(表示 GET)通过 RSS 下载最新的交通信息。比如在清单 14 中,通过添加 ?csz=94101 参数指定了我的邮政编码,于是得到了旧金山最新的交通报告。

清单 14. 旧金山的交通报告(RSS)
% curl -g "http://maps.yahoo.com/traffic.rss?csz=94101" –s
<?xml version="1.0" encoding="ISO-8859-1" ?>
<rss version="2.0">
<channel>
<title>Yahoo! Maps Traffic -- San Francisco,  CA 94101</title>
<link>http://us.rd.yahoo.com/maps/mapresults/trfrssarea/*
? http://maps.yahoo.com/maps_result?csz=
? San+Francisco%2C++CA+94101&country=
? us&lat=37.775&lon=
? -122.4183&trf=1&mag=5</link>
<category>Traffic</category>
<description>Yahoo! Maps Traffic -- 
? San Francisco,  CA 94101</description>
<language>en-us</language>
<ttl>3</ttl>
<lastBuildDate>Fri, 06 May 2005 16:33:59 -0700<
? /lastBuildDate>
<pubDate>Fri, 06 May 2005 18:31:27 CDT<
? /pubDate>
<copyright>Copyright (c) 2005 Yahoo! Inc. 
? All rights reserved.</copyright>
<item>
<title>
Incident, On I-580 At Seminary Ave
</title>
<description>
Traffic Collision, Severity: Major, Started: 04:20pm 05/06/05, 
? Estimated End: 04:50pm 05/06/05, 
? Last Updated: 04:25pm 05/06/05
</description>
<link>http://us.rd.yahoo.com/maps/mapresults/trfrssitem/*
? http://maps.yahoo.com/maps_result?csz=
? San+Francisco%2C++CA+94101&mlt=
? 37.778234&mln=-122.168438&lat=
? 37.775&lon=-122.4183&trf=
? 1&exctrf=1&mag=4</link>
<pubDate>Fri, 06 May 2005 16:20:00 -0700</pubDate>
<category>Incident </category>
<severity>Major</severity>
<endDate>Fri, 06 May 2005 16:50:00 -0700</endDate>
<updatedDate>Fri, 06 May 2005 16:25:00 -0700<
? /updatedDate>
</item>
...

现在可以将 curl 命令的输出通过 XMLStarlet 命令去除其中的描述部分(如清单 15 所示)。

清单 15. 通过 XMLStarlet 处理的交通 RSS
% curl -g "http://maps.yahoo.com/traffic.rss?csz=94101" 
? -s | xml sel -t -m "/rss/channel/item/description" -v "."
Traffic Collision, Severity: Major, Started: 04:20pm 05/06/05, 
? Estimated End: 04:50pm 05/06/05, 
? Last Updated: 04:25pm 05/06/05
Disabled Vehicle, Severity: Moderate, Started: 04:20pm 05/06/05, 
? Estimated End: 04:50pm 05/06/05, 
? Last Updated: 04:25pm 05/06/05
Disabled Vehicle, Severity: Moderate, Started: 04:19pm 05/06/05, 
? Estimated End: 04:49pm 05/06/05, 
? Last Updated: 04:25pm 05/06/05
Pedestrian On The Roadway, Severity: Critical, 
? Started: 04:17pm 05/06/05, 
? Estimated End: 04:47pm 05/06/05, 
? Last Updated: 04:25pm 05/06/05
Traffic Collision, Severity: Major, Started: 04:15pm 05/06/05, 
? Estimated End: 04:45pm 05/06/05, 
? Last Updated: 04:25pm 05/06/05
...

-m 选项从每个项中取出描述,然后使用 -v 选项通过句点(.)输出节点中的文本。

结束语

本文粗略地介绍了这种强大的 XML 工具。有时间的话,不妨试一试 XMLStarlet 的 XSLT 转换功能、方便的转义和取消转义功能以及 XML 格式化功能等等。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Windows和Linux间文本文件格式转换
Linux文件默认权限和umask笔记
SELinux问题讨论,
Linux 文件类型 及文件的扩展名
文件属性及权限管理
Linux文件系统
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服