Hi,
I am parsing through an xml file and wish to add a new component element for stream name="Projects_X" The xml is below:
<?xml version="1.0" encoding="UTF-8"?>
<components>
<stream name="Projects_X">
<component name="comp1" screenshot="/path/to/comp1.jpg" definition_name="/path/to/comp1.xml"/>
<component name="comp2" screenshot="/path/to/comp2.jpg" definition_name="/path/to/comp2.xml"/>
</stream>
<stream name="Projects_Z">
<component name="comp1" screenshot="/path/to/comp1.jpg" definition_name="/path/to/comp1.xml"/>
<component name="comp2" screenshot="/path/to/comp2.jpg" definition_name="/path/to/comp2.xml"/>
<component name="comp3" screenshot="/path/to/comp3.jpg" definition_name="/path/to/comp3.xml"/>
</stream>
</components>
The code I have is the following:
my $streamName="Projects_X";
my $compName = "comp3";
my $screenshot ="/path/to/comp3.jpg";
my $defName="/path/to/comp3.xml";
my $file = "components.xml";
my $twig= new XML::Twig();
$twig->parsefile( $file) || print "Unable to open file $file $!";
my $comps= $twig->root;
my
@cStream=$comps->get_xpath("stream[\
@name='$streamName']");
foreach(
@cStream){ my $newTag= new XML::Twig::Elt( 'component'); # create the element
$newTag->set_att( name => $compName, screenshot => $screenshot, definition_name=>$defName);
$newTag->paste( 'last_child', $_); # paste it in the document
}
$twig->print($file);
By running the above perl script on the command line, I can see that the output has a new element. My problem is redirecting the output to a file. Im not sure how I can redirect the new output to a new file. I have read the xml::twig documentation which says to use the method $twig->print(optionalfilehandle), which I have done, but still does not write the new element to the xml file.
After the script is run the xml file should look like:-
<?xml version="1.0" encoding="UTF-8"?>
<components>
<stream name="Projects_X">
<component name="comp1" screenshot="/path/to/comp1.jpg" definition_name="/path/to/comp1.xml"/>
<component name="comp2" screenshot="/path/to/comp2.jpg" definition_name="/path/to/comp2.xml"/>
<component name="comp3" screenshot="/path/to/comp3.jpg" definition_name="/path/to/comp3.xml"/>
</stream>
<stream name="Projects_Z">
<component name="comp1" screenshot="/path/to/comp1.jpg" definition_name="/path/to/comp1.xml"/>
<component name="comp2" screenshot="/path/to/comp2.jpg" definition_name="/path/to/comp2.xml"/>
<component name="comp3" screenshot="/path/to/comp3.jpg" definition_name="/path/to/comp3.xml"/>
</stream>
</components>
Any help much appreciated
Thanks
Mashuk