2

我的目标是从此 XML 文件中提取两个列表的列表:

<famous_people>
  <famous_person>
    <first_name>Wolfgang</first_name>
    <last_name>Goethe</last_name>
    <year_of_birth>1749</year_of_birth>
    <country_of_origin>Germany</country_of_origin>
  </famous_person>
  <famous_person>
    <first_name>Miguel</first_name>
    <last_name>Cervantes</last_name>
    <widely_known_for>Don Quixote</widely_known_for>
  </famous_person>
</famous_people>

我有兴趣提取的列表是:

[[("first_name","Wolfgang"),("last_name","Goethe"),("year_of_birth","1749"),("country_of_origin","Germany")],[("first_name","Miguel"),("last_name","Cervantes"),("widely_known_for","Don Quixote")]]

我只设法使我感兴趣的所有元组都在一个大的平面列表中,这一点 GHCi 输出证明了这一点:

Prelude> import Text.XML.HXT.Core
Prelude Text.XML.HXT.Core> import Text.HandsomeSoup
Prelude Text.XML.HXT.Core Text.HandsomeSoup> 
Prelude Text.XML.HXT.Core Text.HandsomeSoup> html <- readFile "test.html"
Prelude Text.XML.HXT.Core Text.HandsomeSoup> 
Prelude Text.XML.HXT.Core Text.HandsomeSoup> let doc = readString [] html
Prelude Text.XML.HXT.Core Text.HandsomeSoup> 
Prelude Text.XML.HXT.Core Text.HandsomeSoup> runX $ doc >>> getChildren >>> getChildren >>> getChildren >>> multi (getName &&& deep getText)
[("first_name","Wolfgang"),("last_name","Goethe"),("year_of_birth","1749"),("country_of_origin","Germany"),("first_name","Miguel"),("last_name","Cervantes"),("widely_known_for","Don Quixote")]

如何获得两个列表的所需列表?

4

1 回答 1

2

我使用该listA函数将结果收集到一个列表中。这是我的代码:

module Famous where
import Text.XML.HXT.Core (isElem, hasName, getChildren, getText, listA, runX, readDocument, getName)
import Control.Arrow.ArrowTree (deep)
import Control.Arrow ((>>>), (&&&))
import Text.XML.HXT.Arrow.XmlArrow (ArrowXml)
import Text.XML.HXT.DOM.TypeDefs (XmlTree)

atTag :: ArrowXml a => String -> a XmlTree XmlTree
atTag tag = deep (isElem >>> hasName tag)

parseFamous :: ArrowXml a => a XmlTree [(String, String)]
parseFamous = atTag "famous_person" >>> listA (getChildren >>>
                                               (getName &&& (getChildren >>> getText)))



main :: IO ()
main = do
  let path = "famous.xml"
  result <- runX (readDocument [] path >>> parseFamous)
  print result
于 2013-09-01T21:52:52.340 回答