Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

How to remove elements from XML data?

by waxmop (Beadle)
on Apr 09, 2003 at 19:58 UTC ( #249394=perlquestion: print w/ replies, xml ) Need Help??
waxmop has asked for the wisdom of the Perl Monks concerning the following question:

I need to delete some elements from an XML file, and I'm not sure how to do it intelligently.

I've got an XML file that looks sort of like this:

<opt> <node> <val>1</val> </node> <node> <val>2</val> </node> <node> <val>3</val> </node> </opt>
And I want to remove some arbitrary node based on user input. Here's what I've got so far, assuming that I want to remove the node that has the "val" attribute set to 2:
use strict; use XML::Simple; my $xref = XMLin("<top><node><val>1</val></node><node><val>2</val></no +de><node><val>3</val></node></top>"); my $nodenum = 0; for my $n ( @{$xref->{'node'}} ) { if ( $n->{val} == 2 ) { splice @{$xref->{'node'}}, $nodenum, 1; } $nodenum++; }
I really don't like using the $nodenum++ to track which element I'm iterating at, but I can't think of a better way.

Comment on How to remove elements from XML data?
Select or Download Code
Re: How to remove elements from XML data?
by jasonk (Parson) on Apr 09, 2003 at 20:46 UTC

    IMO, the grep route is the cleanest way:

    $xref->{node} = [grep { $_->{val} != 2; } @{$xref->{node}}];

    We're not surrounded, we're in a target-rich environment!
      I don't understand how you use this. $xref->{node} = [grep { $_->{val} != 2; } @{$xref->{node}}];
      which module you are using??
•Re: How to remove elements from XML data?
by merlyn (Sage) on Apr 09, 2003 at 20:58 UTC
    Another strategy:
    use XML::LibXML; my $d = XML::LibXML->new->parse_string(join "", <DATA>); for my $dead ($d->findnodes(q{/opt/node[val = "2"]})) { $dead->unbindNode; } print $d->toString; __END__ <opt> <node> <val>1</val> </node> <node> <val>2</val> </node> <node> <val>3</val> </node> </opt>
    which results in:
    <?xml version="1.0"?> <opt> <node> <val>1</val> </node> <node> <val>3</val> </node> </opt>

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://249394]
Approved by Enlil
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (12)
As of 2014-09-22 13:53 GMT
Find Nodes?
    Voting Booth?

    How do you remember the number of days in each month?

    Results (194 votes), past polls