我正在从http://hackage.haskell.org/package/xml-conduit-1.1.0.9/docs/Text-XML-Stream-Parse.html解析修改后的 XML
这是它的样子:
<?xml version="1.0" encoding="utf-8"?>
<population xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://example.com">
<success>true</success>
<row_count>2</row_count>
<summary>
<bananas>0</bananas>
</summary>
<people>
<person>
<firstname>Michael</firstname>
<age>25</age>
</person>
<person>
<firstname>Eliezer</firstname>
<age>2</age>
</person>
</people>
</population>
我如何获得每个人的firstname
名单age
?
我的目标是使用 http-conduit 下载这个 xml 然后解析它,但我正在寻找一个解决方案,当没有属性时如何解析(使用 tagNoAttrs?)
这是我尝试过的,我在 Haskell 评论中添加了我的问题:
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad.Trans.Resource
import Data.Conduit (($$))
import Data.Text (Text, unpack)
import Text.XML.Stream.Parse
import Control.Applicative ((<*))
data Person = Person Int Text
deriving Show
-- Do I need to change the lambda function \age to something else to get both name and age?
parsePerson = tagNoAttr "person" $ \age -> do
name <- content -- How do I get age from the content? "unpack" is for attributes
return $ Person age name
parsePeople = tagNoAttr "people" $ many parsePerson
-- This doesn't ignore the xmlns attributes
parsePopulation = tagName "population" (optionalAttr "xmlns" <* ignoreAttrs) $ parsePeople
main = do
people <- runResourceT $
parseFile def "people2.xml" $$ parsePopulation
print people