丑陋的xml输出

时间:2011-05-22 17:30:54

标签: xml haskell haxml

我正在使用HaXml来转换XML文件,而且它们都运行良好。然而,输出HaXml看起来非常难看,主要是因为它几乎在每个结束括号中插入一个换行符。 这是一些生成xml的代码:

writeFile outPath (show . PP.content . head $ test (docContent (posInNewCxt "" Nothing) (xmlParse "" "")))

test = 
    mkElemAttr "test" [("a", literal "1"), ("b", literal "2")]
        [
            mkElem "nested" []
        ]

,这是它生成的输出:

<test a="1" b="2"
  ><nested/></test>

当然,更多元素会更糟糕。

我知道HaXml使用Text.PrettyPrint.HughesPJ进行渲染,但使用了不同的styles  并没有太大变化。

那么,有没有办法改变输出?

1 个答案:

答案 0 :(得分:3)

使用Text.PrettyPrint.renderStyle替换您show的来电,您可以获得一些不同的行为:

import Text.XML.HaXml
import Text.XML.HaXml.Util
import Text.XML.HaXml.Posn
import qualified Text.XML.HaXml.Pretty as PP
import Text.PrettyPrint

main = writeFile "/tmp/x.xml" (renderStyle s . PP.content 
                                             . head $
               test (docContent (posInNewCxt "" Nothing) (xmlParse "" "")))
    where
        s = style { mode = LeftMode, lineLength = 2 }

test = 
    mkElemAttr "test" [("a", literal "1"), ("b", literal "2")]
        [
            mkElem "nested" []
        ]

尝试不同的开箱即用样式:

默认样式

<test a="1" b="2"
  ><nested/></test>

style {mode = OneLineMode}

<test a="1" b="2" ><nested/></test>

style {mode = LeftMode,lineLength = 2}

<test a="1"
b="2"
><nested/></test>

所以你当然可以做一些不同的事情。

如果您不喜欢其中任何一种,可以使用fullRender编写自定义处理器:

fullRender
    :: Mode                     -- Rendering mode
    -> Int                      -- Line length
    -> Float                    -- Ribbons per line
    -> (TextDetails -> a -> a)  -- What to do with text
    -> a                        -- What to do at the end
    -> Doc                      -- The document
    -> a                        -- Result

您的自定义行为可以编入TextDetails函数。