aspose file tools*
The moose likes Beginning Java and the fly likes trimming down a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "trimming down a string" Watch "trimming down a string" New topic
Author

trimming down a string

Jeroen Nouws
Greenhorn

Joined: Jul 14, 2011
Posts: 17
Hey,
I got a byte[] from an xml stream that i want to print to the screen,
this is not really a problem but there's a lot of whitespace in the end and i want it out.
the byte[] is always different but here's an example of the output

as you can see a lot of whitespace :/

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
There are lots of things you could do.
If you get a zero-length line when reading from the file, you could simply ignore it.
If you get a line which is all whitespace, which you can easily find a regular expression for, again, you can ignore it.
You can match for whitespace at the end of the line with a similar regular expression and a line-end boundary match, and use the String.replace() or replaceAll() method on it.

I am sure there are lots of other things you can do. Anybody else got any ideas?

I am not convinced String#trim() is what you want, because it will take the leading whitespace out too, and you would lose your indentation.
Claudiu Chelemen
Ranch Hand

Joined: Mar 25, 2011
Posts: 71

Supposing that you've got a well formed xml in the byte[], I wouldn't bother formatting the xml myself, instead I would use some tool that is specialized on xml handing.

e.g. Maybe I would run it through an org.apache.xml.serialize.XMLSerializer along with the OutputFormat set accordingly.

One of the advantages would be that, in the future, if I get an xml with some other display issues (eg bad identing), the problem would be already solved.

Cheers,
Claudiu
 
Don't get me started about those stupid light bulbs.
 
subject: trimming down a string