How to modify XML data with Perl

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TimEl
    New Member
    • Jun 2007
    • 1

    How to modify XML data with Perl

    Hi.

    Using Perl, I want to modify data in an XML file and print out the entire modified file, not just the elements I modify. In CPAN I have found that XPath allows me to pinpoint the elements that I want to modify. But all of the code examples that I have seen assume that I want to assign the targeted elements to variables, modify each element, and then print only the modified elements out to a file. For example, this code is found at http://search.cpan.org/~mirod/XML-DOM-XPath-0.13/XPath.pm#findno des($path)

    use XML::DOM::XPath ;

    my $parser= XML::DOM::Parse r->new();
    my $doc = $parser->parsefile ("file.xml") ;

    # print all HREF attributes of all CODEBASE elements
    # compare with the XML::DOM version to see how much easier it is to use
    my @nodes = $doc->findnodes( '//CODEBASE[@HREF]/@HREF');
    print $_->getValue, "\n" foreach (@nodes);

    Using the example above, how can I modify the targeted elements WITHIN $doc ITSELF and then print out the entire document, instead of assign the targeted elements to @nodes and print out only the elements in @nodes?

    Any clues would be appreciated.

    Novice Perl programmer,

    Tim
  • Dököll
    Recognized Expert Top Contributor
    • Nov 2006
    • 2379

    #2
    Originally posted by TimEl
    Hi.

    Using Perl, I want to modify data in an XML file and print out the entire modified file, not just the elements I modify. In CPAN I have found that XPath allows me to pinpoint the elements that I want to modify. But all of the code examples that I have seen assume that I want to assign the targeted elements to variables, modify each element, and then print only the modified elements out to a file. For example, this code is found at http://search.cpan.org/~mirod/XML-DOM-XPath-0.13/XPath.pm#findno des($path)
    Code:
    use XML::DOM::XPath;
    
      my $parser= XML::DOM::Parser->new();
      my $doc = $parser->parsefile ("file.xml");
    
      # print all HREF attributes of all CODEBASE elements
      # compare with the XML::DOM version to see how much easier it is to use
      my @nodes = $doc->findnodes( '//CODEBASE[@HREF]/@HREF');
      print $_->getValue, "\n" foreach (@nodes);
    Using the example above, how can I modify the targeted elements WITHIN $doc ITSELF and then print out the entire document, instead of assign the targeted elements to @nodes and print out only the elements in @nodes?

    Any clues would be appreciated.

    Novice Perl programmer,

    Tim
    This looks fetching, Tim, additional info from same site. Please let us know if you'd already seen it:

    http://search.cpan.org/~boewe/XML-YYLex-0.04/YYLex.pm
    Last edited by Dököll; Jun 28 '07, 12:57 AM. Reason: Code tags

    Comment

    Working...