0

I like to write an xml Elem to a file, but I want to set the line separator between each node of the elem, so when opening the file under windows or ubuntu I have the correct format. for example :

val lineSep = System.getProperty("line.separator") 
val xmlData : Elem = <person>
       <firstName>John</firstName>
       <lastName>Doe</lastName>
  <emails>
  <email type=”primary”>john.doe@noone.com</email>
  <email type=”secondary”>john.doe@noone.com</email>
  </emails>
  <address>
  <street>595 Market Street</street>
  <city>San Francisco</city>
  <zip>94105</zip>
  </address>
  </person>

val xmlStreamWriter = XMLOutputFactory.newInstance.createXMLStreamWriter(outputstream)
xmlStreamWriter.writeDTD(xmlData)

How to write it into a file considering the lineSeparator? the XMLOutputFactory have the method setProperty() is it possible to specify the line separator here?

med10
  • 101
  • 7
  • *FYI:* [`writeDTD()`](https://docs.oracle.com/javase/8/docs/api/javax/xml/stream/XMLStreamWriter.html#writeDTD-java.lang.String-) is for writing a [`doctypedecl`](https://www.w3.org/TR/xml/#NT-doctypedecl), i.e. a ` `, not the entire XML document. – Andreas Dec 13 '19 at 17:42
  • If `Elem` is a DOM node, don't use `XMLStreamWriter` for creating XML text. See [How to pretty print XML from Java?](https://stackoverflow.com/q/139076/5221149) – Andreas Dec 13 '19 at 17:46

1 Answers1

0

From The standard Scala XML library - Getting started guide:

To write XML to a file:

scala.xml.XML.save("books.xml", books)

To format XML use the scala.xml.PrettyPrinter to configure the line length and indentation level:

val pp = new scala.xml.PrettyPrinter(24, 4)
pp.format(books)
Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • I do not want to use XLM.save methode because I want to stream the XML content, and the **PrettyPrinter** will format all xml content, I do not want to format the text inside XML node. for example : ` {hello "\n" world} <\text>` with the PrettyPrinter will be outputed like this ` hello world <\text>` the "\n" will be removed – med10 Dec 14 '19 at 13:21
  • In addition to that the PrettyPrinter use internally "\n" as EOL for XML tags. – med10 Dec 14 '19 at 13:44