使用类似awk和sed的工具解析XML的解决方案并不完美。您不能指望XML总是具有人类可读的布局。例如,一些Web服务将省略换行符,导致整个XML文档显示在一行上。
我建议使用xmllint,它具有使用XPATH选择节点的能力,这是专为XML设计的查询语言。
以下命令将选择城市标签:
xmllint --xpath "//city" data.xml
XPath非常有用。它使XML文档的每个部分都可以被寻址:
xmllint --xpath "string(//city[1]/@id)" data.xml
返回字符串 "AT"。
格式不良的 XML 数据
这次返回第一个出现的 "city" 标签。可以使用 xmllint 让结果更易读:
$ xmllint --xpath "//city[1]" data.xml | xmllint -format -
<?xml version="1.0"?>
<city id="AT">
<cityname>Athens</cityname>
<state>GA</state>
<description> Home of the University of Georgia</description>
<population>100,000</population>
<location>Located about 60 miles Northeast of Atlanta</location>
<latitude>33 57' 39" N</latitude>
<longitude>83 22' 42" W</longitude>
</city>
data.xml
在这个数据中,第一个“city”标签出现在同一行上。这是有效的XML。
<data>
<flight>
<airline>Delta</airline>
<flightno>22</flightno>
<origin>Atlanta</origin>
<destination>Paris</destination>
<departure>5:40pm</departure>
<arrival>8:10am</arrival>
</flight>
<city id="AT"> <cityname>Athens</cityname> <state>GA</state> <description> Home of the University of Georgia</description> <population>100,000</population> <location>Located about 60 miles Northeast of Atlanta</location> <latitude>33 57' 39" N</latitude> <longitude>83 22' 42" W</longitude> </city>
<city id="DUB">
<cityname>Dublin</cityname>
<state>Dub</state>
<description> Dublin</description>
<population>1,500,000</population>
<location>Ireland</location>
<latitude>NA</latitude>
<longitude>NA</longitude>
</city>
</data>