src/Pure/General/xml.scala
changeset 27947 b6dc0a396857
parent 27942 5ac9a0f9fad0
child 27948 2638b611d3ce
equal deleted inserted replaced
27946:ec706ad37564 27947:b6dc0a396857
     1 /*  Title:      Pure/General/xml.scala
     1 /*  Title:      Pure/General/xml.scala
     2     ID:         $Id$
     2     ID:         $Id$
     3     Author:     Makarius
     3     Author:     Makarius
     4 
     4 
     5 Minimalistic XML tree values.
     5 Simple XML tree values.
     6 */
     6 */
     7 
     7 
     8 package isabelle
     8 package isabelle
     9 
     9 
       
    10 import org.w3c.dom.{Node, Document}
       
    11 import javax.xml.parsers.DocumentBuilderFactory
       
    12 
       
    13 
    10 object XML {
    14 object XML {
       
    15   /* datatype representation */
       
    16 
    11   type Attributes = List[(String, String)]
    17   type Attributes = List[(String, String)]
    12 
    18 
    13   abstract class Tree
    19   abstract class Tree
    14   case class Elem(name: String, attributes: Attributes, body: List[Tree]) extends Tree
    20   case class Elem(name: String, attributes: Attributes, body: List[Tree]) extends Tree
    15   case class Text(content: String) extends Tree
    21   case class Text(content: String) extends Tree
    38       case Some((s, rest)) => { state = get_nexts(rest); s }
    44       case Some((s, rest)) => { state = get_nexts(rest); s }
    39       case None => throw new NoSuchElementException("next on empty iterator")
    45       case None => throw new NoSuchElementException("next on empty iterator")
    40     }
    46     }
    41   }
    47   }
    42 
    48 
       
    49 
       
    50   /* document object model (DOM) */
       
    51 
       
    52   def DOM(tree: Tree) = {
       
    53     val doc = DocumentBuilderFactory.newInstance.newDocumentBuilder.newDocument
       
    54     def dom_tree(tr: Tree): Node = tr match {
       
    55       case Elem(name, atts, ts) => {
       
    56         val node = doc.createElement(name)
       
    57         for ((name, value) <- atts) node.setAttribute(name, value)
       
    58         for (t <- ts) node.appendChild(dom_tree(t))
       
    59         node
       
    60       }
       
    61       case Text(txt) => doc.createTextNode(txt)
       
    62     }
       
    63     val root_elem = tree match {
       
    64       case Elem(_, _, _) => dom_tree(tree)
       
    65       case Text(_) => dom_tree(Elem("root", Nil, List(tree)))
       
    66     }
       
    67     doc.appendChild(root_elem)
       
    68     doc
       
    69   }
       
    70 
    43 }
    71 }