Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
114 lines (89 sloc) 2.64 KB

Translate xml to json, and due to using of tagstream-conduit, it can parse malformed xml.

And when combined with aeson's parsing facility, you can use it to parse xml to your haskell data type.


Simple example


<test "k1"="v1" "k2"="v2">


        ,"__values":["\n    ccc\n","aaa\n    "]

Siblings with same name got merged.




                  ,"__values":["\n    ","\n        "]
                  ,"__values":["\n    ","\n        "]
         ,"__values":["\n","\n    "]

Parse xml to haskell data type

(You can find real example code in tests/Test.hs)

Say you want to parse following xml

    <addr>foo addr</addr>
    <addr>bar addr</addr>

And You have follow haskell data type

data User = User
  { name :: Text
  , addr :: Text
  } deriving (Eq)

data UserList = UserList
  { userList :: [User]
  , userCount :: Int
  } deriving (Eq)

You want to parse xml into this data type, you can define FromJSON instance for them like this

instance FromJSON User where
    parseJSON (Object o) =
        User <$> o .: "name"
             <*> o .: "addr"
    parseJSON o = typeMismatch "User" o

instance FromJSON UserList where
    parseJSON (Object o) = do
        root <- o .: "users"
        UserList <$> root .: "user"
                 <*> (fmap read (root .: "count"))
        parseUserList (Array a) =
            mapM parseJSON (V.toList a)
        parseUserList o = typeMismatch "UserList.userList" o
    parseJSON o = typeMismatch "UserList" o

Then you can use parseXML provided by this library to parse the xml bytestring to your data type:

a <- parseXML xml_string
assert $ a == UserList [User "foo" "foo addr", User "bar" "bar addr"] 100
Jump to Line
Something went wrong with that request. Please try again.