xmlscalaanti-xml

Can you use antixml to create xml documents?


there are a few examples for using Anti-Xml to extract information from XML documents, but none that I could find of using Anti-Xml to create XML documents. Does Anti-Xml support creating documents, or should I use another library for this (which one?). Does anyone have an example of creating an XML document with Anti-Xml?


Solution

  • Yes, you can build (and serialize) XML documents:

    import com.codecommit.antixml._
    
    val doc = Elem(None, "doc", Attributes(), Map(), Group(
      Elem(None, "foo", Attributes("id" -> "bar"), Map(), Group(Text("baz")))
    ))
    
    val writer = new java.io.StringWriter
    val serializer = new XMLSerializer("UTF-8", true)
    
    serializer.serializeDocument(doc, writer)
    

    You can also use Anti-XML's zippers to do some interesting editing tricks:

    val foos = doc \ "foo"
    val newFoo = foo.head.copy(children = Group(Text("new text!")))
    val newDoc = foos.updated(0, newFoo).unselect
    

    Now newDoc contains the edited document:

    scala> newDoc.toString
    res1: String = <doc><foo id="bar">new text!</foo></doc>
    

    The Zipper that doc \ "foo" returns is different from a NodeSeq in that it carries information about its context, which allows you to "undo" the selection operation done by \.


    Update in response to ziggystar's comment below: if you want something like Scala's XML literals, you can just use convert on any scala.xml.Elem:

    val test: com.codecommit.antixml.Elem = <test></test>.convert
    

    I'd assumed the question was about programmatic creation.