Project

Profile

Help

SAXBuilder and Newline

Added by Anonymous about 17 years ago

Legacy ID: #4265653 Legacy Poster: parmy (parmybrar)

The sample program I have attached, creates two xml files. The content of the xml files are identical: <?xml version="1.0" encoding="UTF-8"?> <root> <message content="A line Another line" /> </root> I then read in one of the xml files using SAXBuilder and output the file, however I lose the newline, I get the following results: <?xml version="1.0" encoding="UTF-8"?> <root> <message content="A line Another line" /> </root> Can anyone help? I'm guessing the problem is caused when I read in the file, however I have no idea how to preserve the newline. Here is code: import java.io.FileInputStream; import java.io.FileOutputStream; import org.jdom.; import org.jdom.output.; import org.jdom.input.*; public class xmlCRTest { public static void main(String[] args) { try{ //1.Create two new xml files called createXML1.xml and createXML2.xml Document jdoc=null; jdoc=new Document(); Element message=new Element("message"); Format fmt = Format.getPrettyFormat(); message.setAttribute("content", "A line\nAnother line"); Element root=new Element("root"); root.getChildren().add(message); jdoc.setRootElement(root); //2.Write the following contents to both files using prettyformat XMLOutputter outp = new XMLOutputter(fmt); outp.output(jdoc, new FileOutputStream("c:\createXML1.xml")); outp.output(jdoc, new FileOutputStream("c:\createXML2.xml")); //4 Get a handle on the newly created file createXML1.xml //5 Read in the xml content String fileName="c:\createXML1.xml"; SAXBuilder sb = new SAXBuilder(); jdoc=sb.build(fileName); fmt.setTextMode(Format.TextMode.PRESERVE); //6 Write out the content to the file createXML1.xml using prettyFileFormat outp = new XMLOutputter(fmt); outp.output(jdoc, new FileOutputStream("c:\createXML1.xml")); }catch(Exception e) { e.printStackTrace(); } } } I am using jdom.jar. Please let me know if you require any more details. Many Thanks Parmy


Replies (1)

RE: SAXBuilder and Newline - Added by Anonymous about 17 years ago

Legacy ID: #4265664 Legacy Poster: Michael Kay (mhkay)

This behaviour is defined in the XML specification: newlines in attribute values are normalized to spaces by an XML parser. If you want the newline retained you have to write it as &_#xa; (without the underscore) Michael Kay

    (1-1/1)

    Please register to reply