Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (20)
As of 2015-07-30 15:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (272 votes), past polls