【发布时间】:2016-03-08 00:36:06
【问题描述】:
这个问题是关于如何使用xmlns 属性等解析xml 内容。我编写了代码来解析它,它可以工作。我会很感激关于它是否可以做得更好的指针。
我有一个 XML 文件 test.xml 如下:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>
<SomeResponse xmlns="https://testsomestuff.org/API/WS/">
<SomeResult>
<html>
<head>
<title>My <b>Title</b></title>
</head>
<body>
<p>Foo bar baz</p>
</body>
</html>
</SomeResult>
</SomeResponse>
</soap:Body></soap:Envelope>
我使用xml-conduit编写了解析“SomeResult”内容的代码:
{-# LANGUAGE OverloadedStrings #-}
import Prelude hiding (readFile)
import Text.XML
import Text.XML.Cursor
import qualified Data.Text as T
import Data.Text.Lazy.Builder (toLazyText)
import Data.Text.Lazy (fromStrict)
main :: IO ()
main = do
doc <- readFile def "test.xml"
let cursor = fromDocument doc
res = fromStrict $ T.concat $ child cursor >>= laxElement "Body" >>= child >>= laxElement "SomeResponse" >>= child >>= laxElement "SomeResult" >>= descendant >>= content
pres = parseText_ def res
cursor2 = fromDocument pres
res2 = child cursor2 >>= element "head" >>= child >>= element "title" >>= descendant >>= content
print $ res2
ghci 中的输出:正确解析:
*Main> main
["My ","Title"]
laxElement 方法是定位SomeResult 内容的好方法吗?如果有更好的方法,我将非常感谢这方面的指点。
另外,我需要在内部主体被转义的地方(如在text.xml 中的SomeResult 下)反向进行http 编码(在构建上述响应的请求时)。这是在使用Text.XML 构建请求时默认处理的事情,还是我必须使用html-entities 之类的东西将内部主体显式转换为转义http?
【问题讨论】:
标签: xml haskell xml-conduit