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.
DocumentBuilderFactory docFactory = DocumentBuilderFactory. newInstance(); DocumentBuilder docBuilder = docFactory. newDocumentBuilder(); Document doc = docBuilder. newDocument();
DOCTYPE> is not mandatory in XML.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With