Greetings Honorable Monks,

I need to replace certain <tm> elements in an XML document with the value of the <tm> element. That is, I need to eliminate the element but retain its content in-place.

For example, If I find:  <tm tmclass="ibm" tmowner="IBM Corporation" tmtype="reg" trademark="AIX">AIX</tm>;

I need to replace the entire <tm>...</tm> element with the text AIX.

I am using XML::LibXML to detect the @tmowner, and trigger the above function. For example:

use strict; use File::Find; use XML::LibXML; my ($file, $parser, $doc, $query, $node, $val, $tmtext); @ARGV=('.'); # search every file in this dir and all subdirs find (\&search, @ARGV); sub search{ $file=$_; if (grep -f && /\.xml$/i, $file){ $parser = XML::LibXML->new(); $doc = $parser->parse_file($file); $query = "//tm"; foreach $node ($doc->findnodes($query)){ $val = $node -> findvalue('@tmowner'); $tmtext = $node -> textContent(); # if we don't own the trademark, replace it with the text if ($val !~ /my_company/i){ ### REPLACE THE TM ELEMENT WITH THE TEXT CONTENT ### print " Replacing trademark element with $tmtext\n"; } } # foreach node } # if grep } # sub search

I have not had any luck with the replaceNode or replaceChild methods for this purpose. I know I could do this with regexps, but that might get messy with all of the preformatting necessary to manage multiple trademarks on one line.

Tips and ideas are appreciated. Thanks for your time.


In reply to Replacing an XPath node with the value of its content by stylechief

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.