Hi,
I am using XML::LibXML module to parse an XML file and read attributes and node values using XPaths. I am able to read the value of nodes all right; but I am having trouble reading the values of attributes - I am not able to get the right approach (XPath and API to read attributes). Please help.
The sample XML file that I am trying to read:
<root>
<head>
<node1 attr1="Node1 Attribute">
Node1 Value
</node1>
</head>
</root>
The PERL script that I am using to read attributes' values :
use XML::LibXML;
$inp = $ARGV[0];
# create object
my $parser = XML::LibXML->new();
# read input XML file
my $inp_tree = $parser->parse_file($inp);
my $inp_root = $inp_tree->getDocumentElement;
my $root_text = $inp_root->toString();
$rule_source = "node1//@attr1";
my @inp_search_nodes = $inp_root->findnodes($rule_source);
my $inp_search_results = scalar @inp_search_nodes;
if ( 0 == $inp_search_results )
{
print "XPath $rule_source not found! \n";
}
else
{
my $path_text = $inp_search_nodes[ 0 ]->findvalue(".");
print "Xpath ->: $path_text\n";
my $val = $inp_search_nodes[ 0 ]->textContent();
+
print "Value of XPath $rule_source : $val \n";
}
I am trying to read the value of the attrbbute "attr1" of the node "node1".
When I use XPath "/head/node1/@attr1", I get this result when I try toi run the PERL scri[t shown above:
XPath error : Invalid expression
/head/node1/
^
When I use this XPath - "head/node1/@attr1", I get the same error listed above
When I use this XPath - "head/node1@attr1", the code prints the value of the node node1 and NOT the value of the attribute.
When I use this XPath - "/head/node1@attr1", I get this error: "XPath /head/node1 not found"
So, which Xpath should I use to read the value of the attribute of a node?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.