Haskell |如何从深度嵌套的数据结构中获取值?

时间:2018-12-18 13:13:08

标签: haskell data-structures lens lenses

我是haskell的初学者,我正在尝试通过一些基本的分析来了解有关该语言的更多信息。

我有一些代码可以解析XML文件并生成该文件

[ Element
    { elName = QName
        { qName = "title"
        , qURI = Nothing
        , qPrefix = Nothing
        }
    , elAttribs = []
    , elContent =
        [ Text
            ( CData
                { cdVerbatim = CDataText
                , cdData = "This string is what I want to obtain" -- string to view.
                , cdLine = Just 27
                }
            )
        ]
    , elLine = Just 27
    }
]

Element只是XML library's数据类型

我想要做的是获取字符串"This string is what I want to obtain"

我不确定在不展开整个数据结构的情况下如何做。我发现这种方式确实很混乱且容易出错。

我做了一些常规研究,发现了Lens库,尽管有一些教程,但我仍在努力解析嵌套的数据结构。

这是我要解析的XML文件

<GoodreadsResponse>
    <Request>
        <authentication>true</authentication>
        <key>HOKCk4yYS8UjyducqmgRw</key>
        <method>search_search</method>
    </Request>
    <search>
        <query>fantasy</query>
        <results-start>1</results-start>
        <results-end>20</results-end>
        <total-results>35221</total-results>
        <source>Goodreads</source>
        <query-time-seconds>0.21</query-time-seconds>
        <results>
            <work>
                <id type="integer">2384</id>
                <books_count type="integer">51</books_count>
                <ratings_count type="integer">78825</ratings_count>
                <text_reviews_count type="integer">3357</text_reviews_count>
                <original_publication_year type="integer">2002</original_publication_year>
                <original_publication_month type="integer">2</original_publication_month>
                <original_publication_day type="integer">18</original_publication_day>
                <average_rating>4.17</average_rating>
                <best_book type="Book">
                    <id type="integer">84136</id>
                    <title>Fantasy Lover (Hunter Legends Series #1)</title>
                    <author>
                        <id type="integer">4430</id>
                        <name>Sherrilyn Kenyon</name>
                    </author>
                    <image_url>https://images.gr-assets.com/books/1348332807m/84136.jpg</image_url>
                    <small_image_url>https://images.gr-assets.com/books/1348332807s/84136.jpg</small_image_url>
                </best_book>
            </work>
            <work>
                <id type="integer">6734901</id>
                <books_count type="integer">42</books_count>
                <ratings_count type="integer">18358</ratings_count>
                <text_reviews_count type="integer">985</text_reviews_count>
                <original_publication_year type="integer">2010</original_publication_year>
                <original_publication_month type="integer" nil="true"/>
                <original_publication_day type="integer" nil="true"/>
                <average_rating>4.26</average_rating>
                <best_book type="Book">
                    <id type="integer">6542645</id>
                    <title>Fantasy in Death (In Death, #30)</title>
                    <author>
                        <id type="integer">17065</id>
                        <name>J.D. Robb</name>
                    </author>
                    <image_url>https://s.gr-assets.com/assets/nophoto/book/111x148-bcc042a9c91a29c1d680899eff700a03.png</image_url>
                    <small_image_url>https://s.gr-assets.com/assets/nophoto/book/50x75-a91bf249278a81aabab721ef782c4a74.png</small_image_url>
                </best_book>
            </work>
       ...
       ...

2 个答案:

答案 0 :(得分:2)

由于xml本身并未定义任何光学元件,因此您需要另一个封装来定义。 @ Li-yaoXia找到了一个:lens-xml

 #!/usr/bin/env cabal
 {- cabal:
 build-depends: base
              , xml
              , lens
              , lens-xml
 -}
 {-# LANGUAGE OverloadedStrings #-}

 import Control.Lens
 import Text.XML.Light.Types
 import Text.XML.Light.Lens

 x = [ Element
         { elName = QName
             { qName = "title"
             , qURI = Nothing
             , qPrefix = Nothing
             }
         , elAttribs = []
         , elContent =
             [ Text
                 ( CData
                     { cdVerbatim = CDataText
                     , cdData = "This string is what I want to obtain" -- string to view.
                     , cdLine = Just 27
                     }
                 )
             ]
         , elLine = Just 27
         }
     ]

 main :: IO ()
 main = print (x ^? ix 0 . elContentL . ix 0 . _Text . cdDataL)

您可以使用cabal的最新版本来运行它:

$ cabal new-run Main.hs
<<lots of build output snipped>>
Just "This string is what I want to obtain"

免责声明:我不确定我是否同意将lens用于此任务的想法。就个人而言,我倾向于首先将XML转换为数据类型(当XML不符合预期的架构时显示错误消息),然后处理该数据类型。但是,您确实要求基于lens的解决方案...

答案 1 :(得分:1)

使用列表推导和记录访问器非常清楚:

get :: [Element] -> [String]
get es = [cdData c | e <- es, Text c <- elContent e ]

Text c模式将自动过滤出Elem e中的任何CRef selContent e值。

一旦了解到,对于列表来说,=<<的意思是concatMap,您可以使用以下方式保存一些字符

get :: [Element] -> [String]
get es = [cdData c | Text c <- elContent =<< es]

另外,如果您只想在cdDatacdVerbatim时使用CDataText,则可以添加该条件。

get :: [Element] -> [String]
get es = [cdData c | Text c <- elContent =<< es, cdVerbatim c == CDataText ]