3

如何访问通过 XPath 指定的属性的值xml_grep

我试过了:

# svn info http://unladen-swallow.googlecode.com/svn/trunk/ --xml > x
# cat x
<?xml version="1.0"?>
<info>
<entry
   kind="dir"
   path="trunk"
   revision="1171">
<url>http://unladen-swallow.googlecode.com/svn/trunk</url>
<repository>
<root>http://unladen-swallow.googlecode.com/svn</root>
<uuid>05521daa-c0b4-11dd-bb00-bd6ab96fe29a</uuid>
</repository>
<commit
   revision="1171">
<author>ebo@4geeks.de</author>
<date>2010-08-21T18:17:31.382601Z</date>
</commit>
</entry>
</info>



# xml_grep uuid x --text_only
05521daa-c0b4-11dd-bb00-bd6ab96fe29a
# xml_grep //info/entry/@path x --text_only # correct XPath syntax
error: unrecognized expression in handler: '//info/entry/@path' at /usr/bin/xml_grep line 198
# xml_grep //info/entry/[@path] x --text_only
# # no output

我查看了在线帮助页面,但唯一与属性匹配的语法太冗长了:

# xml_grep '*[@path]' x
<?xml version="1.0" ?>
<xml_grep version="0.7" date="Wed Aug 28 15:22:13 2013">
<file filename="x">
  <entry kind="dir" path="trunk" revision="1171">
    <url>http://unladen-swallow.googlecode.com/svn/trunk</url>
    <repository>
      <root>http://unladen-swallow.googlecode.com/svn</root>
      <uuid>05521daa-c0b4-11dd-bb00-bd6ab96fe29a</uuid>
    </repository>
    <commit revision="1171">
      <author>ebo@4geeks.de</author>
      <date>2010-08-21T18:17:31.382601Z</date>
    </commit>
  </entry>
</file>
</xml_grep>
#

什么是正确的语法?

4

1 回答 1

4

xml_grep是一个使用 PerlXML::Twig模块的非常简单的工具。类似XPath 的表达式的允许语法在此处记录。似乎不可能像这样提取属性的值。

我建议改用该xpath程序:

$ xpath x '//entry/@path'
Found 1 nodes:
-- NODE --
 path="trunk"

该程序应与XML::Xpath.


如果一切都失败了,那就自己动手吧。我选择的武器是XML::LibXML

use strict; use warnings;
use XML::LibXML;

my ($file, $query) = @ARGV;

my $xml = XML::LibXML->load_xml(location => $file);
print $xml->findvalue($query), "\n";

然后$ perl xpath-findvalue.pl x '//entry/@path'。输出:trunk

于 2013-08-28T19:51:43.923 回答