7
votes

I have the following file log.xml:

<entry>
  <message>Line 1
  Line 2 and so on</message>
</entry>

On CentOS 5.4 using xmlstarlet 1.0.1 if I run the following command, while removing linefeed in message:

xml sel -t -m //entry -v "translate(message,'&#xa;' ,'@')" log.xml

The result is:

Line 1@  Line 2 and so on

On CentOS 6 using xmlstarlet:

1.3.1
compiled against libxml2 2.7.6, linked with 20706
compiled against libxslt 1.1.26, linked with 10126

I'll receive:

Line 1
  Line 2 nd so on

Note "and" converted to nothing. I suppose it's not problem of xmlstarlet, but rather some change in libxslt.

Any ideas how to fix it?

UPDATE

Added problem with transform of letter "a" to nothing.

3
@EeroHelenius Not sure it's the same problem :( - dimba
Don't know for sure, but maybe the line endings are other than you expect: sourceforge.net/mailarchive/message.php?msg_id=28142284 - Mark Veenstra

3 Answers

6
votes

You can solve this in a general way by defining a variable containing the value of a line break:

--var linebreak -n --break 

Then use that variable as the second argument of the translate function:

xml sel -t -m //entry
        --var linebreak -n --break
        -v "translate(message, \$linebreak ,'@')"
        log.xml
3
votes

&#xa; only represents a newline character when the XPath expression is itself in an XML file (such as an XSLT stylesheet). I suspect what's happening here is that when you say

translate(message,'&#xa;' ,'@')

on the command line, the '&#xa;' is being treated as a five character string, and thus you're telling translate to replace & with @ and also to replace all of #, x, a and ; with nothing.

Try a literal newline using ctrl-V

xml sel -t -m //entry -v "translate(message,'<ctrl-V><CR>' ,'@')" log.xml

(i.e. press ctrl-V followed by carriage return when typing the command - it will appear on your screen as ^M).

2
votes

I don't know about xmlstarlet, but you could try Xidel:

xidel log.xml -e '//message/translate(., $line-ending, "@")'

I wrote all of it, from parser to query engine, so it has no dependencies and behaves the same on all systems.