代码之家  ›  专栏  ›  技术社区  ›  bob9123

使用Scala XML从XML检索ref/url数据时出现问题

  •  1
  • bob9123  · 技术社区  · 7 年前

    XML示例:

    <?xml version="1.0" encoding="UTF-8"?>
    <entry>
       <author>
          <name>/u/Kobe_to_Boston</name>
          <uri>https://www.reddit.com/user/Kobe_to_Boston</uri>
       </author>
       <id>t3_94t5in</id>
       <link href="https://www.reddit.com/r/hiphopheads/comments/94q6ks/travis_scott_stop_trying_to_be_god_ft_kid_cudi/" />
       <updated>2018-08-05T16:38:29+00:00</updated>
       <title>The Weeknd - The Hills</title>
    </entry>
    

    使用 Scala XML Library . 我试图从Reddit RSS feed获取各种数据。

    例如,获取有关Reddit帖子标题的信息。以下代码为:

    val redditPostTitle = (XML.loadString(xmlContent) \ "entry" \ "title").head.text 
    //assume xmlContent variable is the contains the XML above
    

    上面的工作。

    现在,问题是,我想从“link-ref”标签中检索数据。我尝试过各种组合:

    val redditPostUrl = (XML.loadString(xmlContent) \ "entry" \ "link href").head.text 
    

    但我得到了一个空字符串。我想要的是:

    "https://www.reddit.com/r/hiphopheads/comments/94q6ks/travis_scott_stop_trying_to_be_god_ft_kid_cudi/
    

    解决方案:解决方案是:

    (XML.loadString(hhhContent) \ "entry" \\ "link" \\ "@href").text
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   proximator    7 年前

    这很管用:

    object Example extends App {
    
      val feed=
        <entry>
          <author>
            <name>/u/Kobe_to_Boston</name>
            <uri>https://www.reddit.com/user/Kobe_to_Boston</uri>
          </author>
          <id>t3_94t5in</id>
          <link href="https://www.reddit.com/r/hiphopheads/comments/94q6ks/travis_scott_stop_trying_to_be_god_ft_kid_cudi/" />
          <updated>2018-08-05T16:38:29+00:00</updated>
          <title>The Weeknd - The Hills</title>
        </entry>
    
      println(feed \\ "link" \ "@href")
    
    }
    
    推荐文章