[英]How do I combine results from zip-filter queries on an xml tree in Clojure?
I want to combine the results of three zip-filter queries on an xml tree. 我想在xml树上结合三个zip-filter查询的结果。 The XML I am parsing looks like this: 我正在解析的XML看起来像这样:
<someroot>
<publication>
<contributors>
<person_name>
<surname>Surname A</surname>
</person_name>
<person_name>
<given_name>Given B</given_name>
<surname>Surname B</surname>
<suffix>Suffix B</suffix>
</person_name>
</contributors>
</publication>
</someroot>
From this example you can see that <given_name>
and <suffix>
are optional - only <surname>
is required. 在此示例中,您可以看到<given_name>
和<suffix>
是可选的 - 只需要<surname>
。 Here in lies my problem - if I run three separate queries the responses I get will be out of kilter with each other: 这就是我的问题 - 如果我运行三个单独的查询,我得到的响应将彼此不同:
(xml-> xml :publication :contributors :person_name :given_name text)
(xml-> xml :publication :contributors :person_name :surname text)
(xml-> xml :publication :contributors :person_name :suffix text)
After running these three queries I will be left with three sequences whose cardinalities do not match; 运行这三个查询后,我将留下三个基数不匹配的序列; given_name
and suffix
will be length 1 while surname
will be length 2. This makes it impossible for me to combine the components of each name. given_name
和suffix
长度为1,而surname
长度为2.这使得我无法组合每个名称的组件。 I need to write a single query that will perform this name concatenation during sequence construction. 我需要编写一个查询,在序列构建期间执行此名称连接。
I'm looking at the very sparse documentation for clojure.contrib.zip-filter.xml
and can't figure out how I could do this (or if it is even possible). 我正在查看clojure.contrib.zip-filter.xml
的非常稀疏的文档,并且无法弄清楚我是如何做到的(或者甚至可能)。 Unfortunately I am a Clojure (and Lisp) newbie! 不幸的是,我是一个Clojure(和Lisp)的新手! Can anyone point out how I can write a query that will concatenate three other embedded queries? 任何人都可以指出我如何编写一个将连接其他三个嵌入式查询的查询?
You can get all the person subtrees in one step (xml-> xmlzip :publication :contributors :person_name) then get the name parts if they exist (xml1-> personzip :surname text) and combine them to the result you want like so: 您可以一步获取所有人员子树(xml-> xmlzip:publication:contributors:person_name)然后获取名称部分(如果它们存在(xml1-> personzip:surname文本)并将它们组合到您想要的结果中:
(use 'clojure.contrib.zip-filter.xml)
(defn format-name
[surname given suffix]
(str surname (if given (str ", " given)) (if suffix (str ", " suffix))))
(defn get-names
[xz]
(map (juxt
#(xml1-> % :surname text)
#(xml1-> % :given_name text)
#(xml1-> % :suffix text))
(xml-> xz :publication :contributors :person_name)))
(let [x (clojure.zip/xml-zip (clojure.xml/parse "foo.xml"))]
(map (partial apply format-name) (get-names x)))
Results in ("Surname A" "Surname B, Given B, Suffix B") 结果(“姓氏A”“姓氏B,给定B,后缀B”)
I suppose an alternative solution is to 我想另一种解决方案是
(xml-> xml :publication :contributors :person_name)
and then process each <person_name>
later on. 然后再处理每个<person_name>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.