我有使用clj-xpath库从xml中提取内容的函数(仅限内容)。
(ns example
(:use [clj-xpath.core]))
(def data-url
"http://api.eventful.com/rest/events/search?app_key=4H4Vff4PdrTGp3vV&keywords=music&location=New+York&date=Future")
(defn xml-data [url] (slurp url))
(defn defxmldoc [url]
(xml->doc (xml-data url)))
(defn contents-only [url root-tag tags]
(vec(map(fn [item]
(into {}
(map (fn [tag]
[tag ($x:text (str "./" (name tag))item)])tags)))
(take 5 ($x root-tag (defxmldoc url))))))
函数调用看起来像这样
(contents-only data-url "/search/events/event" [:title :url])
当我尝试从嵌套标记中提取文本时,它适用于非嵌套标记,即
<performers>
<performer>
<id>P0-001-000009049-1</id>
<url>...</url>
<name>Lindsey Buckingham</name>
<short_bio>Rock</short_bio>
<creator>TomAzoff</creator>
<linker>evdb</linker>
</performer>
函数调用如下所示
(contents-only data-url "/search/events/event" [:title :url :name])
我得到RuntimeException错误,来自xml({:children ...)的xpath(./ name)clj-xpath.core / throwf(core.clj:26)的结果(0)多于(或少于)1
如何更改仅限内容的功能,以便我也可以传递嵌套标记?
答案 0 :(得分:2)
最快的方法:在"./"
函数中将".//"
更改为contents-only
。
user> (first (contents-only data-url "/search/events/event" [:title :id :name]))
{:title "Legally Blonde the Musical", :id "P0-001-000351944-7", :name "Legally Blonde The Musical"}
user>
正如xpath documentation中所述,.//name
将从当前节点开始选择所有节点name
,无论层次结构在何处。
如果name
不是唯一的,它可能不是您想要的,并且一种方式是在您指定的路径中明确,例如。
(contents-only data-url "/search/events/event"
[[:title]
[:performers :performer :id]
[:performers :performer :name]])
并有一些帮助函数,如:
(defn build-path
([sep kys] (build-path nil sep kys))
([root sep kys]
(->> kys (map name) (interpose sep)
(concat (when root (list root sep))) (apply str))))
(defn path
"build a path from a collection"
[t]
(build-path "." \/ t))
user> (path [:performers :performer :id])
"./performers/performer/id"
(defn path-key
"Transform [:a :b :c] into :a-b-c"
[t]
(->> t (build-path \-) keyword))
user> (path-key [:performers :performer :id])
:performers-performer-id
然后contents-only
变为:
(defn contents-only2 [url root-tag tags]
(vec (map(fn [item]
(into {}
(map (fn [tag]
[(path-key tag) ($x:text (path tag) item)])
tags)))
(take 5 ($x root-tag (defxmldoc url))))))
结果:
user> (first (contents-only2 data-url "/search/events/event"
[[:title]
[:performers :performer :id]
[:performers :performer :name]]))
{:title "Legally Blonde the Musical", :performers-performer-id "P0-001-000351944-7", :performers-performer-name "Legally Blonde The Musical"}
user>