update xml attribute value

176 views
Skip to first unread message

siyu798

unread,
Jun 2, 2011, 1:32:46 PM6/2/11
to clo...@googlegroups.com
Hi,
  Does anyone know how to update xml element attribute value on the zipper data structure?

I have something like

<root>
    <element1 name="x1" description="d1"/>
    <element2 name="x2" description="d2"/>
</root>

(:require (clojure [xml :as xml] [zip :as zip]) 
     [clojure.contrib.zip-filter.xml :as zf])

(let
  [src (-> "c:/my.xml" io/file xml/parse zip/xml-zip)
   edf (zf/xml1-> src :root :element1)
   n    (-> (zf/attr :description) (zip/replace "dddd"))])

and this is giving me java.lang.ClassCastException: java.lang.Character cannot be cast to clojure.lang.Associative (test-xml-zip.clj:0)

Thanks,

Allen Johnson

unread,
Jun 2, 2011, 2:12:51 PM6/2/11
to clo...@googlegroups.com

Given that 'loc is the proper location in your zipper:

(zip/edit loc assoc-in [:attrs :description] "new value")

Allen

siyu798

unread,
Jun 2, 2011, 2:26:24 PM6/2/11
to clo...@googlegroups.com
Thanks Allen, it works, I did not know the loc can be treated like a hash.

siyu

Allen Johnson

unread,
Jun 2, 2011, 2:38:49 PM6/2/11
to clo...@googlegroups.com
> Thanks Allen, it works, I did not know the loc can be treated like a hash.

'loc itself isn't a map even though zip/edit makes it seem that way.
Behind the scenes zip/edit calls (zip/node loc) which will return a
map, at least in the case of this xml example. zip/edit then applies
the function you provided (assoc-in) to this map plus any supplied
args. The result of this replaces the node at loc.

https://github.com/clojure/clojure/blob/59b65669860a1f33825775494809e5d500c19c63/src/clj/clojure/zip.clj#L210

Allen

Reply all
Reply to author
Forward
0 new messages