Clojure XML解析 [英] Clojure XML Parsing
问题描述
我找不到任何关于如何解析xml文档和访问元素的信息。
我发现了两种方法来解析xml文档
(clojure.zip/xml-zip(clojure.xml / parse文件))
和
(parse-seq文件)
但我似乎可以找到有关如何处理结果结构的任何信息?
源文件是关于如何查询结果的zip-query.clj,但似乎也失踪了。
p>假设您有以下xml来解析您的文件:
< high-node>
< low-node>我的文本< / low-node>
< / high-node>
您加载 clojure.xml
:
user => (使用'clojure.xml)
当解析时,xml将具有以下结构:
{:tag:high-node,:attrs nil,:content [{:tag:low-node,:attrs nil,:content [my text]}]}
,然后您可以对文件的内容获取低节点
的内容:
user = ($ [xml-seq
(parse(java.io.File.file)))
:when(=:low-node(:tag x))]
(:content x)))
(my text)
<同样,如果你想访问低节点信息的整个列表,你可以改变:当谓词为
(=(: high-node(:tag x)))
:
user => ($ [xml-seq
/ pre>
(parse(java.io.File.file)))
:when(=:high-node(:tag x))]
(:content x)))
({:tag:low-node,:attrs nil,:content [my text]})
这是因为关键字可以作为函数操作。请参见有关Clojure中的列表和其他内容的问题和数据结构:关键字
I can not find any info on how to parse xml documents and access elements.
I have found two ways to parse the xml document
(clojure.zip/xml-zip (clojure.xml/parse file))
and
(parse-seq file)
but i can seem to find any info on how to process the resulting structure?
Source file's refers to zip-query.clj on how to query the result but that seems to missing too.
解决方案Suppose you have the following xml to parse in your file:
<high-node> <low-node>my text</low-node> </high-node>
you load
clojure.xml
:user=> (use 'clojure.xml)
when parsed, the xml will have the following structure:
{:tag :high-node, :attrs nil, :content [{:tag :low-node, :attrs nil, :content ["my text"]}]}
and then you can seq over the content of the file to get the content of the
low-node
:user=> (for [x (xml-seq (parse (java.io.File. file))) :when (= :low-node (:tag x))] (first (:content x))) ("my text")
Similarly, if you wanted to have access to the entire list of information on low-node, you would change the
:when
predicate to(= (:high-node (:tag x)))
:user=> (for [x (xml-seq (parse (java.io.File. file))) :when (= :high-node (:tag x))] (first (:content x))) ({:tag :low-node, :attrs nil, :content ["my text"]})
This works because the keywords can operate as functions. See Questions about lists and other stuff in Clojure and Data Structures: Keywords
这篇关于Clojure XML解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!