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

Formatting XML string?

Brady Diggs
Ranch Hand

Joined: Jun 26, 2008
Posts: 42
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

Joined: Oct 27, 2005
Posts: 19670
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Or if you want to stick to the standard Java API, then:
Brady Diggs
Ranch Hand

Joined: Jun 26, 2008
Posts: 42
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

Joined: Oct 27, 2005
Posts: 19670
    
  18

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
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

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?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Formatting XML string?