Friday 15 May 2015

perl - Find and replace text using XML::LibXML -


I want to find the text attached to the tilde ( ~ ) and include the text in some strings Want to replace ~ t1it ~ with ~ it ~ in the XML file, then save the result to another file. I know how to use XPath to get the text and how to change it, but I do not know how to put the replaced text in their places and output it.

Here my input is XML:

    

This is my Perl script:

  Use Strict; Use warnings; Use XML :: LibXML; #use XML :: LibXML :: Text; Cwd use 'abs_path'; My $ x_name = abs_path ($ ARGV [0]); My $ doc = XML :: LibXML- & gt; Load_xml (location = & gt; $ x_name, no_blanks = & gt; 1); My $ xpath_expression = '/ chapter / section / paragraph / math'; My @ nodes = $ doc- & gt; Searchnode ($ xpath_expression); Prefer my $ node (@ nodes) {my $ content = $ node- & gt; TextContent; $ Content = ~ roy # \ ~ ROM \ ~ # ~ T1rom ~ # sg; Print $ content, "\ n"; }   

Here is my desired output:

     

One possibility: code of setData method > XML :: LibexML :: text :

  #! Use / usr / bin / perl warnings; Strict use; Use XML :: LibXML; My $ x_name = $ ARGV [0]; My $ doc = XML :: LibXML- & gt; Load_xml (location = & gt; $ x_name, no_blanks = & gt; 1); My $ xpath_expression = '/ chapter / section / paragraph / math / text ()'; My @ nodes = $ doc- & gt; Searchnode ($ xpath_expression); For my $ node (@ nodes) {my $ content = $ node- & gt; ToString; $ Content = ~ s # \ ~ rom \ ~ # ~ T1rom ~ # sg; $ Node- & gt; SetData ($ content); } $ Doc- & gt; ToFile ($ x_name. '.new', 1);    

No comments:

Post a Comment