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.

Replies are listed 'Best First'.
•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.

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??

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://249394]
Approved by Enlil
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2017-12-13 17:16 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (371 votes). Check out past polls.