Based on your description I'm not 100% sure which of the following two things you want to achieve, so let me address both:
A) Get a list of all child nodes of the Parent node
One solution is to match the Parent node via an XPath expression, and then call the childNodes method on it (which is what tangent already suggested above).
An alternative solution is to use an asterisk wildcard directly in the XPath expression, e.g. in your example the expression passed to findnodes would become '//Parent/*'.
However if there are multiple Parent nodes in the document, this would return all their children as one flat list, whereas tangent's solution allows you to handle each set separately.
Another difference is that the asterisk expression only matches element nodes, whereas the childNodes method also lists text or CDATA nodes (including whitespace strings in between the child elements, although there is an alternative method called nonBlankChildNodes which avoids that).
If you are indeed only interested in the child elements, but want to process each set separately in case of multiple Parent nodes, you could either combine childNodes with a check for nodeName (like tangent's solution does), or use a stand-alone asterisk-query:
my $doc = XML::LibXML->load_xml( ... );
foreach my $parent ($doc->findnodes('//Parent')) {
my @childElements = $parent->findnodes('*');
# ...do stuff with @childElements...
}
B) Get a string serialization of the Parent node, but with the actual Parent start/end tags stripped...
...akin to the .innerHTML property available in JavaScript/DOM.
XML::LibXML does not provide this feature, and the reason is probably that, unlike with HTML, an XML snippet requires a single root element in order to be valid XML.
You could still achieve it by getting the list of child nodes (see section A above), calling the toString method on each, and concatenating the resulting strings:
my $doc = XML::LibXML->load_xml( ... );
foreach my $parent ($doc->findnodes('//Parent')) {
print "Found Parent node with the following XML content:";
print innerXML($parent);
}
sub innerXML { join '', map { $_->toString } shift->childNodes(); }
Or by calling toString directly on the Parent node, and using regexes to try and strip off the outer start/end tags (but this will be messy and error-prone).
|