The functions to support using XPath in Clojure.
Source Code
1
;The code was implemented by caichao@amazon.com
2 ;You could use the code anyway, but should keep the comments
3 ;Created 2012.10
4 (ns clojure.ccsoft.xml
5 (:require [clojure.xml :as xml]))
6
7 ( import ' (java.io StringReader)
8 ' (java.io ByteArrayInputStream))
9
10 (defn xml - structure [xml - txt]
11 [ (xml / parse ( -> xml - txt
12 (.getBytes)
13 (ByteArrayInputStream.)
14 )
15 )]
16 )
17
18 (defn node [tag xmlStruct]
19
20 (first (filter #( = (:tag % ) tag) (:content xmlStruct)))
21 )
22
23 (defn node [path xml - txt]
24 (loop [path path
25 xml - content (xml - structure xml - txt)
26 ]
27 (let [current - tag (first path) current - elem (first xml - content)]
28 ( if ( = (:tag current - elem ) current - tag)
29
30 ( if ( = (count path) 1 )
31 current - elem
32 (recur (rest path) (:content current - elem ))
33 )
34 ( if ( > (count xml - content) 1 )
35 (recur path (rest xml - content))
36 )
37 )
38 )
39 )
40 )
2 ;You could use the code anyway, but should keep the comments
3 ;Created 2012.10
4 (ns clojure.ccsoft.xml
5 (:require [clojure.xml :as xml]))
6
7 ( import ' (java.io StringReader)
8 ' (java.io ByteArrayInputStream))
9
10 (defn xml - structure [xml - txt]
11 [ (xml / parse ( -> xml - txt
12 (.getBytes)
13 (ByteArrayInputStream.)
14 )
15 )]
16 )
17
18 (defn node [tag xmlStruct]
19
20 (first (filter #( = (:tag % ) tag) (:content xmlStruct)))
21 )
22
23 (defn node [path xml - txt]
24 (loop [path path
25 xml - content (xml - structure xml - txt)
26 ]
27 (let [current - tag (first path) current - elem (first xml - content)]
28 ( if ( = (:tag current - elem ) current - tag)
29
30 ( if ( = (count path) 1 )
31 current - elem
32 (recur (rest path) (:content current - elem ))
33 )
34 ( if ( > (count xml - content) 1 )
35 (recur path (rest xml - content))
36 )
37 )
38 )
39 )
40 )
How to Use
(def cmd
-
example
"
<command>
< header >
< type > script </ type >
< transaction_id > 12345 </ transaction_id >
</ header >
< body >
println 3 + 4 ;
</ body >
</ command > " )
(node [:command :header :transaction_id] cmd - example)
< header >
< type > script </ type >
< transaction_id > 12345 </ transaction_id >
</ header >
< body >
println 3 + 4 ;
</ body >
</ command > " )
(node [:command :header :transaction_id] cmd - example)