1

I have used below code to get the regex but not working properly.. Please suggest..

<?xml version='1.0'?> <root> <category cname='CH1' id='C1'> <subcat sname='SCName1' sid='SC1'> 

I want to get sname & sid attributes value of SCName1 & SC1. I've used below code

use File::Slurp; my $filename='nba.xml'; my @lines = read_file( $filename ) ; foreach (@lines) { $_=~/sname\s*=\s*'([^']+)'.*?sid\s*=\s*'([^']+)'/g; print "$1,$2\n"; $comp1="$1"; $comp2="$2"; } 

Thanks in advance!!!!!!

2 Answers 2

4

You need to use XML parser but not regular expressions to parse XML!

use XML::LibXML; my $doc = XML::LibXML->load_xml(string => <<'EOT'); <root> <category cname='CH1' id='C1'/> <subcat sname='SCName1' sid='SC1'/> </root> EOT my $xpc = XML::LibXML::XPathContext->new($doc); my $sname = $xpc->findvalue('//subcat/@sname'); my $sid = $xpc->findvalue('//subcat/@sid'); 
Sign up to request clarification or add additional context in comments.

Comments

1

I found another way to do this using regex....

foreach(@lines) { if($_=~/sname\s*=\s*'([^']+)'.*?sid\s*=\s*'([^']+)'/g) { $scatval="$1"; if ($scatval eq $subCateGory) { $scatid="$2"; $scat_flag=1; } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.