-2

Hi I have an XML file which I want to remove first line of it using Perl and replace it with only one word. Would you please let me know how one could manage it?

Fro example, let' we have an XML file which includes some lines as:

<SquishReport version="2.1" xmlns="http://www.froglogic.com/XML2">
<test name="test">
.
.
.

which after removing and adding the desired line I would have:

<SquishReport>
<test name="test">
.
.
Royeh
  • 433
  • 5
  • 21
  • 2
    You want to delete the root node? That sound like an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What are you actually trying to accomplish? Please give some (complete) samples if input/output XML. – Sobrique Oct 27 '15 at 12:08
  • @Sobrique Please see the edited version – Royeh Oct 27 '15 at 12:11
  • 1
    OK, I understand the question a bit better, and have answered accordingly. However I think this is still an XY problem - I would question why you need to delete the root node attributes? – Sobrique Oct 27 '15 at 12:24
  • Because when I have root node with attribute then the code could not read children, otherwise it works very fine. – Royeh Oct 27 '15 at 13:44
  • Which code? Because chances are that's not doing XML properly, and that's where your problem actually lies. – Sobrique Oct 27 '15 at 13:47
  • Please take a look at this question: http://stackoverflow.com/questions/33370690/perl-could-not-read-the-xml-files – Royeh Oct 27 '15 at 14:33
  • Yes, "In my code". What are you using "in your code" that can't handle well formed XML? Because that's bad news for all concerned. – Sobrique Oct 27 '15 at 14:36
  • XPath 1 and namespaces don't go very well together :-( – reinierpost Oct 27 '15 at 15:48

1 Answers1

3

With XML::Twig:

Replace "root element + attributes" with just "root element":

#!/usr/bin/env perl
use strict;
use warnings;
 
use XML::Twig;

my $twig = XML::Twig -> parse ( \*DATA );
$twig -> root -> del_atts;
$twig -> set_pretty_print('indented_a');
$twig -> print;

__DATA__
<SquishReport version="2.1" xmlns="http://www.froglogic.com/XML2">
<test name="test"> </test>
</SquishReport>

Prints:

<SquishReport>
  <test name="test"> </test>
</SquishReport>

Note -

$twig -> set_pretty_print('indented_a');

Can change file content - from the docs on XML::Twig:

WARNING: this option leaves the document well-formed but might make it invalid (not conformant to its DTD).

So turning off pretty printing if that's a concern would be the appropriate choice.

Community
  • 1
  • 1
Sobrique
  • 52,974
  • 7
  • 60
  • 101
  • 1
    `$twig -> set_pretty_print('indented_a');` can modify the file. Best not to use it "by default". – ikegami Oct 27 '15 at 14:31
  • `keep_spaces => 1` in the `new` will leave all whitespace untouched (except for line returns in attribute values which are normalized by the parser) – mirod Oct 27 '15 at 14:43
  • I haven't been tripped up by it yet, but I'll amend the answer. – Sobrique Oct 27 '15 at 14:46