Do not use XML::Simple
. Both XML::LibXML and XML::Twig are far better, to say the least.
I can't show how to pull data from the first XML since it's not shown, but here is how to edit that other XML file using XML::LibXML
. I suggest to rewrite the first operation with this module as well.
Find the node via an XPath expression and replace element's text-node children: remove and add.
use warnings;
use strict;
use XML::LibXML;
# ... your code that establishes the $session_id variable ...
my $session_id = 'SAMPLE_ID';
my $filename = 'another.xml';
my $doc = XML::LibXML->load_xml(location => $filename);
my ($node) = $doc->findnodes('//sessionid');
$node->removeChildNodes();
$node->appendText($session_id);
# print $doc->toString;
$doc->toFile('edited_' . $filename); # or just $filename to overwrite
Documentation on XML::LibXML most relevant to this is for Text, Element, and Node classes. See also pages for Parser and Document. Here is XPath
specification and a tutorial (w3schools).
A few comments.
Instead of loading the file directly we can create the parser object first
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($filename);
With the parser on hand we can use methods for its configuration outside of the constructor (while stilll before parsing), what provides more flexibility.
There are other ways to change data, depending on your purpose. For example
$node->firstChild->setData($session_id);
is more specific. It uses firstChild
from XML::LibXML::Node
If a node has child nodes this function will return the first node in the child list.
and setData
from XML::LibXML::Text
This function sets or replaces text content to a node. The node has to be of the type "text", "cdata" or "comment".
This works for that one child, "the first node in the child list."
We can also get the text node by findnodes('//sessionid/text()')
and use setData
(on that one child) directly, if the element has children. You probably want to do as in the answer though.