2013-07-14 34 views
0

我正在閱讀XML文件,並且希望將「print」中的XPath替換爲「@href =」*?releaseStatus = RELEASED「,以便我使它通用來獲得實例中第一次出現怎樣才能做到這一點在Perl中使用XML :: LibXML在XML中使用元字符進行字符串搜索

use XML::LibXML; 

my $parser = XML::LibXML->new(); 
my $doc = $parser->parse_file("type_book.xml"); 

for my $chapter_node ($doc->findnodes('/book/contents')) 
{ 
print $chapter_node->findvalue('locator[@href ="/book/isbn/979-0-4444-1000-17/book-part/chapter/bk444444ch1?releaseStatus=RELEASED"]/@title'); 
} 

XML文件:??

<book> 
<contents> 
<locator href="/book/isbn/979-0-4444-1000-17/book-part/chapter/bk444444ch1? releaseStatus=RELEASED" role="http://www.abc.org/roles/book-part-locator" title="Photonic crystal light-emitting sources"> 
</locator> 
<locator href="/book/isbn/979-0-4444-1000-17/book-part/chapter/bk444444ch1?releaseStatus=RELEASED&amp;format=pdf" role="http://www.abc.org/roles/book-part-pdf-locator" title="Photonic crystal light-emitting sources"> 
</locator> 
<locator href="/book/isbn/979-0-4444-1000-17/book-part/chapter/bk444444ch1?releaseStatus=RELEASED&amp;format=epub" role="http://www.abc.org/roles/book-part-epub-locator" title="Photonic crystal light-emitting sources"> 
</locator> 
</contents> 
</book> 

回答

2

夠好

locator[contains(@href, "?releaseStatus=RELEASED")]/@title 

使用XPath 2個功能(不知道是否通過XML ::的libxml支持)

locator[fn:matches(@href, "^.*(\?|&)releaseStatus=RELEASED(&|$)")]/@title 

您可能需要fnhttp://www.w3.org/2005/xpath-functions關聯。

+0

它應該總是隻返回「releaseStatus = RELEASED」,不適用於所有像「releaseStatus = RELEASED&amp;」等 – Robie

+0

調整爲新信息 – ikegami

+0

@ikegami:你確定libxml2支持XPath 2嗎?請參閱http://stackoverflow.com/questions/6586896/does-libxml2-support-xpath-2-0-or-not –