Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to add DOCTYPE to Scala XML?

Tags:

html

xml

scala

How can I make this miminal HTML5 in Scala XML: <!DOCTYPE html><title></title><p></p></html>?

Of course it's simple to make an HTML-like XML in Scala:

> val html = <html><title></title><p></p></html>
html: scala.xml.Elem = <html><title></title><p></p></html>

However, how can I inject a DOCTYPE attribute prefixed in the html tag?

Two routes I tried:
Using the scala.xml.Document and scala.xml.DocType, but both seemed predicated on writing out a file or stream, whereas I'm just keeping this XML object in memory. Seemed like too much ceremony.

Using Attribute,

> import scala.xml.{Null, Text, Attribute}
> val d = <html /> % Attribute(None, "!DOCTYPE", Text(""), Null)
d: scala.xml.Elem = <html !DOCTYPE=""></html>

which is close, but not a prefixed attribute and with a naughty assignment.

like image 626
Noel Avatar asked Mar 30 '11 19:03

Noel


People also ask

How do I create a doctype XML?

DocumentBuilderFactory docFactory = DocumentBuilderFactory. newInstance(); DocumentBuilder docBuilder = docFactory. newDocumentBuilder(); Document doc = docBuilder. newDocument();

Is doctype required in XML?

DOCTYPE> is not mandatory in XML.


1 Answers

You can use XML's write method that takes a java.io.Writer instead of a File. Using java.io.StringWriter is straight forward:

val w = new java.io.StringWriter()
val html = <html><body><p>Que pasa?!</p></body></html>
xml.XML.write(w, html, "UTF-8", xmlDecl = false, doctype = 
   xml.dtd.DocType("html", xml.dtd.SystemID("about:legacy-compat"), Nil))
w.toString
like image 140
0__ Avatar answered Oct 31 '22 21:10

0__