我有以下XML片段:
...
<Setting name="HOST1">server1</Setting>
<Setting name="HOST2">server2</Setting>
<Setting name="HOST3">server4</Setting>
<Setting name="HOST4">server8n12</Setting>
...
<!-- Many more such declarations all with the attribute of the form "HOSTNN" -->
我使用LibXML查找与HOST匹配的节点
my $dom = XML::LibXML->load_xml(location => $xml)
or die "Unable to create LibXML object";
my $root = $dom->getDocumentElement();
my @hostnames = $root->findnodes('//Setting[contains(@name,"HOST")]');
是否可以在XPath表达式中指定一类字符,类似于在regexp中指定的字符?例如,Perl正则表达式:
/^HOST\d+?$/
答案 0 :(得分:3)
//Setting[starts-with(@name,"HOST")]
[translate(substring-after(@name,"HOST"),
"0123456789",
"")=""]
编辑:我没有看到限定符。以上内容将与Setting[@name="HOST"]
匹配。更严格:
//Setting[starts-with(@name,"HOST")]
[number(substring-after(@name,"HOST")) =
substring-after(@name,"HOST")]
编辑2 :上面的内容不够严格(它会匹配“HOST2.1”)。遗憾。
//Setting[starts-with(@name,"HOST")]
[substring-after(@name,"HOST")]
[translate(substring-after(@name,"HOST"),
"0123456789",
"")=""]
答案 1 :(得分:0)
我的xpath有点生疏,但我认为这可能有用(或者我将css与xpath结合起来)
Setting[@name^="HOST"]