Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: Replace XML tag names.

by CountZero (Bishop)
on May 04, 2010 at 06:30 UTC ( #838250=note: print w/replies, xml ) Need Help??

in reply to Replace XML tag names.

As a start-tag is not allowed to contain whitespace (since whitespace is used as a delimiter between the tag and the attributes) or the > character, the character class of excluded characters should only contain these two characters. For good measure I have added ? and ! to exclude xml-headers, doctype elements, processings instructions and the like.

s{(<[^\s?!>]+)}{(my $tagname = $1 ) =~ tr/.//d;$tagname;}eg;

Yes that will cause the substitiution part to trigger even when there are no dots in the tagname, but it makes the whole of the regex much simpler and easier to understand and debug.


A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^2: Replace XML tag names.
by Jenda (Abbot) on May 04, 2010 at 11:25 UTC

    I think you should also handle the <![CDATA[...]]> sections.

    $xml =~ s{(?:(<!\[CDATA\[.*?\]\]>)|(<[^\s?!>]+))}{ $1 or do {(my $tagname = $2 ) =~ tr/.//d;$tagname;} }seg; # or ... sligthly more efficient for XMLs with most tags without the d +ots $xml =~ s{(?:(<!\[CDATA\[.*?\]\]>)|(<[^\s?!>\.]+\.[^\s?!>]+))}{ $1 or do {(my $tagname = $2 ) =~ tr/.//d;$tagname;} }seg; # and now even more efficient thanks to moving the &lt; outside the or $xml =~ s{<(?:(!\[CDATA\[.*?\]\]>)|(<[^\s?!>\.]+\.[^\s?!>]+))}{ '<'. ($1 or do {(my $tagname = $2 ) =~ tr/.//d;$tagname;} ) }seg;

    Enoch was right!
    Enjoy the last years of Rome.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://838250]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2017-11-23 03:27 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (328 votes). Check out past polls.