'How to access an element of an xml which ends with specific characters using perl
my xml file has nodes as follows, However the name of second child node is not always the same. But it always ends with the same extension, in this case text. How can I access those nodes. Please help. I have used XML::LibXML in perl.
<Root>
<ele1>"text"</ele1>
<name attr="xxxxx">
<value>10</value>
<xxtext>90</xxtext>
</name>
<name attr="yyyy">
<value>30</value>
<yytext>100</yytext>
</name>
</Root>
The code:
my $parser = XML::LibXML->load_xml(location=>$xml);
foreach my $sec ($parser->findnodes('/Root/name)) {
my $value=$sec->findnodes('./value'); print $value,"\n";
my $ias=$sec->findnodes('./*text'); -------------? This is where I am facing problem.
}
It works to find the tag value but I couldn't access the elements with tags ending with ias in this case. I was wondering if there is a way to access these type of tags. Please help.
Solution 1:[1]
If the position of the target element among its siblings is known, you can address it through xpath functions last()or position():
my $ias=$sec->findnodes('./*[last()]');
or
my $ias=$sec->findnodes('./*[position() = 2]');
Alternative
You may also address (parts of) the element name of the target nodes which is provided through the name() function:
my $ias=$sec->findnodes('*[ends-with(name(), "text")]');
However, the ends-with() function requires XPath 2 support.
Note
There are various sites to test XPath expressions, eg. here. Substitute //name for . in the XPath expressions from your code when trying.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
