xmlhaskellhxt

Rendering CDATA with Haskell XHT Library


How can I make HXT library to output CDATA?

For example running test in this snippet will result in

<?xml version="1.0" encoding="UTF-8"?>
<texts>hello&lt;br>world!</texts>

import Text.XML.HXT.Core

hello :: ArrowXml a => a XmlTree XmlTree
hello =
  mkelem "texts" [] [txt "hello<br>world!"]

test = runX $
  root [] [hello]
  >>>
  writeDocument [withIndent yes] "somefile.xml"

But I need it to render:

<?xml version="1.0" encoding="UTF-8"?>
<texts><![CDATA[hello<br>world!]]></texts>

Can HXT automatically detect if CDATA is necessary?


Solution

  • I didn't find such an option while grepping over the source of hxt, but you always can call mkCdata explicitly to construct a CDATA text node:

    import Text.XML.HXT.Core
    
    hello :: ArrowXml a => a XmlTree XmlTree
    hello =
      mkelem "texts" [] [constA "hello<br>world!" >>> mkCdata]
    

    And you may define a function simliar to txt, in the same manner how txt is defined in the source:

    import qualified Text.XML.HXT.DOM.XmlNode as XN
    
    txtCdata :: ArrowXml a => String -> a n XmlTree
    -- XN.mkCdata :: XmlNode n => String -> n, XmlTree is an instance of XmlNode
    -- constA :: Arrow a => c -> a b c, b is free
    txtCdata = constA . XN.mkCdata
    
    hello :: ArrowXml a => a XmlTree XmlTree
    hello =
      mkelem "texts" [] [txtCdata "hello<br>world!"]