-
StackOverflow 文件
-
Perl Language 教程
-
XML 解析
-
使用 XMLTwig 進行解析
#!/usr/bin/env perl
use strict;
use warnings 'all';
use XML::Twig;
my $twig = XML::Twig->parse( \*DATA );
#we can use the 'root' method to find the root of the XML.
my $root = $twig->root;
#first_child finds the first child element matching a value.
my $title = $root->first_child('title');
#text reads the text of the element.
my $title_text = $title->text;
print "Title is: ", $title_text, "\n";
#The above could be combined:
print $twig ->root->first_child_text('title'), "\n";
## You can use the 'children' method to iterate multiple items:
my $list = $twig->root->first_child('list');
#children can optionally take an element 'tag' - otherwise it just returns all of them.
foreach my $element ( $list->children ) {
#the 'att' method reads an attribute
print "Element with ID: ", $element->att('id') // 'none here', " is ", $element->text,
"\n";
}
#And if we need to do something more complicated, we an use 'xpath'.
#get_xpath or findnodes do the same thing:
#return a list of matches, or if you specify a second numeric argument, just that numbered match.
#xpath syntax is fairly extensive, but in this one - we search:
# anywhere in the tree: //
#nodes called 'item'
#with an id attribute [@id]
#and with that id attribute equal to "1000".
#by specifying '0' we say 'return just the first match'.
print "Item 1000 is: ", $twig->get_xpath( '//item[@id="1000"]', 0 )->text, "\n";
#this combines quite well with `map` to e.g. do the same thing on multiple items
print "All IDs:\n", join ( "\n", map { $_ -> att('id') } $twig -> get_xpath('//item'));
#note how this also finds the item under 'summary', because of //
__DATA__
<?xml version="1.0" encoding="utf-8"?>
<root>
<title>some sample xml</title>
<first key="value" key2="value2">
<second>Some text</second>
</first>
<third>
<fourth key3="value">Text here too</fourth>
</third>
<list>
<item id="1">Item1</item>
<item id="2">Item2</item>
<item id="3">Item3</item>
<item id="66">Item66</item>
<item id="88">Item88</item>
<item id="100">Item100</item>
<item id="1000">Item1000</item>
<notanitem>Not an item at all really.</notanitem>
</list>
<summary>
<item id="no_id">Test</item>
</summary>
</root>