• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

trimming down a string

 
Jeroen Nouws
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48374
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 75
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic