我需要从文档中深入选择一个XML节点并对其进行转换,然后将其移动到另一个位置。
此示例取自Haskell cafe,并稍作更改:
选择//d/e/f,然后更改f上的内容,并将新的f节点移动到a下。
<a>
...
<d>
<e>
<f>some data to change
</f>
</e>
</d>
...
</a> 我需要多次执行这种操作,所以如果更新操作是可组合的就更好了。
我正在研究xml-conduit包,但它似乎缺少DOM操作函数,完成这类任务的最好方法是什么?
发布于 2015-02-25 22:19:58
我对HXT非常陌生,所以可能还有更好的方法,但我解决了一个类似的问题:
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE Arrows, NoMonomorphismRestriction #-}
module Abc where
import Text.XML.HXT.Core
moveElts :: ArrowXml a => a XmlTree XmlTree
moveElts =
processTopDown (
-- Insert <f>'s under <a>:
slurpF `when` hasName "a"
>>>
-- and remove the old <f>'s:
removeChildrenExcept "f" `when` neg (hasName "a")
)
where
removeChildrenExcept tag =
replaceChildren (getChildren >>> neg (hasName tag))
slurpF = proc a -> do
elts <- deep (hasName "f") -< a
returnA (insertChildrenAt 0 (constA elts)) -<< a
-- Test:
test :: IO ()
test = runX (readDocument [withValidate no] "abc.xml"
>>> moveElts
>>> writeDocumentToString [withIndent yes])
>>= putStrLn . headhttps://stackoverflow.com/questions/22448120
复制相似问题