Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Formatting XML string?

 
Brady Diggs
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does anyone know a quick way to input a string of XML and format the text?
I've looked at the API (J2SE 6), but nothing looked useful. Seems like this
ought to have been done before...

Really all I'm trying to do is to wrap the lines in a JEditTextArea (a very early version
that doesn't have wrap functionality ). I just thought since it is XML, I could use
a formatter.

Thanks in advance for your help!
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JDOM has a "pretty" format you can get using Format.getPrettyFormat(). You can then use that in an XMLOutputter instance. The biggest drawback is, however, that it requires you to put the entire XML document into your memory as a org.jdom.Document. Check out JDOM's SAXBuilder for creating a Document from a file or other source.
 
Paul Clapham
Sheriff
Pie
Posts: 20955
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or if you want to stick to the standard Java API, then:
 
Brady Diggs
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both very good suggestions, fellows. Thanks.

Isn't there an easy way to break a String into lines
and then insert each line as a new line in a Document?
I can't append \n to break the lines. That's the rub.
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Transformer and the JDOM formatter have no notion of strings and lines - they work on more abstract notions like documents, elements and attributes.
 
Paul Clapham
Sheriff
Pie
Posts: 20955
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brady Diggs wrote:Isn't there an easy way to break a String into lines
and then insert each line as a new line in a Document?

It wouldn't take more than about 10 lines of code to do either of the XML-based options already suggested. What's "not easy" about that?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic