Sponsored Content
Top Forums Shell Programming and Scripting Bash XML Parsing using Perl XPath Post 302485658 by fpmurphy on Wednesday 5th of January 2011 10:06:49 PM
Old 01-05-2011
My version of Perl xpath does not have a -e option and the command line syntax appears to be different. However you should be able to get the idea.

To retrieve the count of the bread nodes:
Code:
$ xpath input.xml "count(//bread)"  2>/dev/null
2
$

To retrieve the contents of the first type node:
Code:
$ xpath input.xml "//bread[position() = 1]/type/text()" 2>/dev/null
sourdough
$

To retrieve the contents of the second type node:
Code:
$ xpath input.xml "//bread[position() = 2]/type/text()" 2>/dev/null
pumpernickel
$

This User Gave Thanks to fpmurphy For This Post:
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Conversion of bash parsing script to perl?

I need help with a perl parsing script. I have some error logs on a windows machine that I need to parse from a text file, but I know nothing about perl. I usually run this bash script on my linux box and it does just what I need. How would I do the same thing with perl and port it to my windows... (2 Replies)
Discussion started by: cstovall
2 Replies

2. UNIX for Advanced & Expert Users

xml parsing error in perl

******************PERL VERSION************************ This is perl, v5.8.1 built for i386-linux-thread-multi ERROR!!!!---Undefined subroutine &main::start called at /usr/lib/perl5/vendor_perl/5.8.0/i386-linux-thread-multi/XML/Parser/Expat.pm line 469. *********************PERL... (1 Reply)
Discussion started by: bishweshwar
1 Replies

3. Shell Programming and Scripting

Perl parsing compared to Ksh parsing

#! /usr/local/bin/perl -w $ip = "$ARGV"; $rw = "$ARGV"; $snmpg = "/usr/local/bin/snmpbulkget -v2c -Cn1 -Cn2 -Os -c $rw"; $snmpw = "/usr/local/bin/snmpwalk -Os -c $rw"; $syst=`$snmpg $ip system sysName sysObjectID`; sysDescr.0 = STRING: Cisco Internetwork Operating System Software... (1 Reply)
Discussion started by: popeye
1 Replies

4. Shell Programming and Scripting

Random XML Parsing - using Perl

Given the XML: <?xml version="1.0" encoding="UTF-8"?> <reference> <refbody> <section> <p> <ul> <li><xref href="file1.dita#anchor" /></li> <li><xref href="file2.dita#anchor" /></li> </ul> </p> </section> <section> <p> <xref href="file3.dita#anchor" /> </p> <p> <xref... (4 Replies)
Discussion started by: ricksj
4 Replies

5. Shell Programming and Scripting

parsing XML result by using perl?

for some reasons, i need to parse the XML result by using perl. for instance, this is a sample XML result: <Response> <status>success</status> <answer>AAA::AAA</answer> <answer>BBB::BBB</answer> </Response> then i can use this way : my @output = (); foreach my $parts (@all) ##@all... (2 Replies)
Discussion started by: tiger2000
2 Replies

6. Shell Programming and Scripting

Extract TAG name and XPATH from XML file via shellscript

Hi, Here is a sample xml file and expected output. I need to extract the element/tag name (not value) and xpath (sample output.txt). But the main problem is I put here one simple xml file where I can clearly see the number of elements, but in real time I have a xml file which have over 500... (18 Replies)
Discussion started by: BithunC
18 Replies

7. Shell Programming and Scripting

Help in parsing XML output file in perl.

Hi I have an XML output like : <?xml version="1.0" encoding="ISO-8859-1" ?> - <envelope> - <body> - <outputGetUsageSummary> - <usgSumm rerateDone="5"> - <usageAccum accumId="269" accumCaptn="VD_DP_AR" inclUnits="9999999.00" inclUnitsUsed="0.00" shared="false" pooled="false"... (7 Replies)
Discussion started by: rkrish
7 Replies

8. Shell Programming and Scripting

XML: parsing of the Google contacts XML file

I am trying to parse the XML Google contact file using tools like xmllint and I even dived into the XSL Style Sheets using xsltproc but I get nowhere. I can not supply any sample file as it contains private data but you can download your own contacts using this script: #!/bin/sh # imports... (9 Replies)
Discussion started by: ripat
9 Replies

9. Shell Programming and Scripting

XML parsing

i have xml output in below format... <AlertsResponse> <Alert id="11216" name="fgdfg"> <AlertActionLog timestamp="1356521629778" user="admin" detail="Recovery Alert"/> </Alert> <Alert id="11215" name="gdfg <AlertActionLog timestamp="1356430119840" user=""... (12 Replies)
Discussion started by: vivek d r
12 Replies

10. Shell Programming and Scripting

Parsing XML (and insert data) then output data (bash / Solaris)

Hi folks I have a script I wrote that basically parses a bunch of config and xml files works out were to add in the new content then spits out the data into a new file. It all works - apart from the xml and config file format in the new file with XML files the original XML (that ends up in... (2 Replies)
Discussion started by: dfinch
2 Replies
XML::LibXML::XPathContext(3)				User Contributed Perl Documentation			      XML::LibXML::XPathContext(3)

NAME
XML::LibXML::XPathContext - XPath Evaluation SYNOPSIS
my $xpc = XML::LibXML::XPathContext->new(); my $xpc = XML::LibXML::XPathContext->new($node); $xpc->registerNs($prefix, $namespace_uri) $xpc->unregisterNs($prefix) $uri = $xpc->lookupNs($prefix) $xpc->registerVarLookupFunc($callback, $data) $data = $xpc->getVarLookupData(); $callback = $xpc->getVarLookupFunc(); $xpc->unregisterVarLookupFunc($name); $xpc->registerFunctionNS($name, $uri, $callback) $xpc->unregisterFunctionNS($name, $uri) $xpc->registerFunction($name, $callback) $xpc->unregisterFunction($name) @nodes = $xpc->findnodes($xpath) @nodes = $xpc->findnodes($xpath, $context_node ) $nodelist = $xpc->findnodes($xpath, $context_node ) $object = $xpc->find($xpath ) $object = $xpc->find($xpath, $context_node ) $value = $xpc->findvalue($xpath ) $value = $xpc->findvalue($xpath, $context_node ) $bool = $xpc->exists( $xpath_expression, $context_node ); $xpc->setContextNode($node) my $node = $xpc->getContextNode; $xpc->setContextPosition($position) my $position = $xpc->getContextPosition; $xpc->setContextSize($size) my $size = $xpc->getContextSize; $xpc->setContextNode($node) The XML::LibXML::XPathContext class provides an almost complete interface to libxml2's XPath implementation. With XML::LibXML::XPathContext is is possible to evaluate XPath expressions in the context of arbitrary node, context size, and context position, with a user-defined namespace-prefix mapping, custom XPath functions written in Perl, and even a custom XPath variable resolver. EXAMPLES
Namespaces This example demonstrates "registerNs()" method. It finds all paragraph nodes in an XHTML document. my $xc = XML::LibXML::XPathContext->new($xhtml_doc); $xc->registerNs('xhtml', 'http://www.w3.org/1999/xhtml'); my @nodes = $xc->findnodes('//xhtml:p'); Custom XPath functions This example demonstrates "registerFunction()" method by defining a function filtering nodes based on a Perl regular expression: sub grep_nodes { my ($nodelist,$regexp) = @_; my $result = XML::LibXML::NodeList->new; for my $node ($nodelist->get_nodelist()) { $result->push($node) if $node->textContent =~ $regexp; } return $result; }; my $xc = XML::LibXML::XPathContext->new($node); $xc->registerFunction('grep_nodes', &grep_nodes); my @nodes = $xc->findnodes('//section[grep_nodes(para,"search(ing|es)?")]'); Variables This example demonstrates "registerVarLookup()" method. We use XPath variables to recycle results of previous evaluations: sub var_lookup { my ($varname,$ns,$data)=@_; return $data->{$varname}; } my $areas = XML::LibXML->new->parse_file('areas.xml'); my $empl = XML::LibXML->new->parse_file('employees.xml'); my $xc = XML::LibXML::XPathContext->new($empl); my %variables = ( A => $xc->find('/employees/employee[@salary>10000]'), B => $areas->find('/areas/area[district='Brooklyn']/street'), ); # get names of employees from $A working in an area listed in $B $xc->registerVarLookupFunc(&var_lookup, \%variables); my @nodes = $xc->findnodes('$A[work_area/street = $B]/name'); METHODS
new my $xpc = XML::LibXML::XPathContext->new(); Creates a new XML::LibXML::XPathContext object without a context node. my $xpc = XML::LibXML::XPathContext->new($node); Creates a new XML::LibXML::XPathContext object with the context node set to $node. registerNs $xpc->registerNs($prefix, $namespace_uri) Registers namespace $prefix to $namespace_uri. unregisterNs $xpc->unregisterNs($prefix) Unregisters namespace $prefix. lookupNs $uri = $xpc->lookupNs($prefix) Returns namespace URI registered with $prefix. If $prefix is not registered to any namespace URI returns "undef". registerVarLookupFunc $xpc->registerVarLookupFunc($callback, $data) Registers variable lookup function $prefix. The registered function is executed by the XPath engine each time an XPath variable is evaluated. It takes three arguments: $data, variable name, and variable ns-URI and must return one value: a number or string or any "XML::LibXML::" object that can be a result of findnodes: Boolean, Literal, Number, Node (e.g. Document, Element, etc.), or NodeList. For convenience, simple (non-blessed) array references containing only XML::LibXML::Node objects can be used instead of an XML::LibXML::NodeList. getVarLookupData $data = $xpc->getVarLookupData(); Returns the data that have been associated with a variable lookup function during a previous call to "registerVarLookupFunc". getVarLookupFunc $callback = $xpc->getVarLookupFunc(); Returns the variable lookup function previously registered with "registerVarLookupFunc". unregisterVarLookupFunc $xpc->unregisterVarLookupFunc($name); Unregisters variable lookup function and the associated lookup data. registerFunctionNS $xpc->registerFunctionNS($name, $uri, $callback) Registers an extension function $name in $uri namespace. $callback must be a CODE reference. The arguments of the callback function are either simple scalars or "XML::LibXML::*" objects depending on the XPath argument types. The function is responsible for checking the argument number and types. Result of the callback code must be a single value of the following types: a simple scalar (number, string) or an arbitrary "XML::LibXML::*" object that can be a result of findnodes: Boolean, Literal, Number, Node (e.g. Document, Element, etc.), or NodeList. For convenience, simple (non-blessed) array references containing only XML::LibXML::Node objects can be used instead of a XML::LibXML::NodeList. unregisterFunctionNS $xpc->unregisterFunctionNS($name, $uri) Unregisters extension function $name in $uri namespace. Has the same effect as passing "undef" as $callback to registerFunctionNS. registerFunction $xpc->registerFunction($name, $callback) Same as "registerFunctionNS" but without a namespace. unregisterFunction $xpc->unregisterFunction($name) Same as "unregisterFunctionNS" but without a namespace. findnodes @nodes = $xpc->findnodes($xpath) @nodes = $xpc->findnodes($xpath, $context_node ) $nodelist = $xpc->findnodes($xpath, $context_node ) Performs the xpath statement on the current node and returns the result as an array. In scalar context, returns an XML::LibXML::NodeList object. Optionally, a node may be passed as a second argument to set the context node for the query. The xpath expression can be passed either as a string or or as a XML::LibXML::XPathExpression object. find $object = $xpc->find($xpath ) $object = $xpc->find($xpath, $context_node ) Performs the xpath expression using the current node as the context of the expression, and returns the result depending on what type of result the XPath expression had. For example, the XPath "1 * 3 + 52" results in an XML::LibXML::Number object being returned. Other expressions might return a XML::LibXML::Boolean object, or a XML::LibXML::Literal object (a string). Each of those objects uses Perl's overload feature to ``do the right thing'' in different contexts. Optionally, a node may be passed as a second argument to set the context node for the query. The xpath expression can be passed either as a string or or as a XML::LibXML::XPathExpression object. findvalue $value = $xpc->findvalue($xpath ) $value = $xpc->findvalue($xpath, $context_node ) Is exactly equivalent to: $xpc->find( $xpath, $context_node )->to_literal; That is, it returns the literal value of the results. This enables you to ensure that you get a string back from your search, allowing certain shortcuts. This could be used as the equivalent of <xsl:value-of select=``some_xpath''/>. Optionally, a node may be passed in the second argument to set the context node for the query. The xpath expression can be passed either as a string or or as a XML::LibXML::XPathExpression object. exists $bool = $xpc->exists( $xpath_expression, $context_node ); This method behaves like findnodes, except that it only returns a boolean value (1 if the expression matches a node, 0 otherwise) and may be faster than findnodes, because the XPath evaluation may stop early on the first match (this is true for libxml2 >= 2.6.27). For XPath expressions that do not return node-set, the method returns true if the returned value is a non-zero number or a non-empty string. setContextNode $xpc->setContextNode($node) Set the current context node. getContextNode my $node = $xpc->getContextNode; Get the current context node. setContextPosition $xpc->setContextPosition($position) Set the current context position. By default, this value is -1 (and evaluating XPath function "position()" in the initial context raises an XPath error), but can be set to any value up to context size. This usually only serves to cheat the XPath engine to return given position when "position()" XPath function is called. Setting this value to -1 restores the default behavior. getContextPosition my $position = $xpc->getContextPosition; Get the current context position. setContextSize $xpc->setContextSize($size) Set the current context size. By default, this value is -1 (and evaluating XPath function "last()" in the initial context raises an XPath error), but can be set to any non-negative value. This usually only serves to cheat the XPath engine to return the given value when "last()" XPath function is called. If context size is set to 0, position is automatically also set to 0. If context size is positive, position is automatically set to 1. Setting context size to -1 restores the default behavior. getContextSize my $size = $xpc->getContextSize; Get the current context size. setContextNode $xpc->setContextNode($node) Set the current context node. BUGS AND CAVEATS
XML::LibXML::XPathContext objects are reentrant, meaning that you can call methods of an XML::LibXML::XPathContext even from XPath extension functions registered with the same object or from a variable lookup function. On the other hand, you should rather avoid registering new extension functions, namespaces and a variable lookup function from within extension functions and a variable lookup function, unless you want to experience untested behavior. AUTHORS
Ilya Martynov and Petr Pajas, based on XML::LibXML and XML::LibXSLT code by Matt Sergeant and Christian Glahn. HISTORICAL REMARK
Prior to XML::LibXML 1.61 this module was distributed separately for maintenance reasons. AUTHORS
Matt Sergeant, Christian Glahn, Petr Pajas VERSION
2.0008 COPYRIGHT
2001-2007, AxKit.com Ltd. 2002-2006, Christian Glahn. 2006-2009, Petr Pajas. perl v5.16.2 2012-10-22 XML::LibXML::XPathContext(3)
All times are GMT -4. The time now is 10:31 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy