Elisp Parse XML and then search for specific values.
I have an XML file that contains several nested groups, e.g.
<?xml encoding="utf-8"?>
<MainNode
attribute1='values'
attribute2='values'/>
<SubNode1 attribute1='values'>
<Sub-SubNode1 attribute1='values'> ;; I want this value, only if
<Node-Of-Interest> ;; This exists
<Attribute1 value="value1"/> ;; And this is a specific value
<Attribute2 value="value2"/>
</Node-Of-Interest>
</Sub-SubNode1>
</SubNode1>
<SubNode1 attribute1='values'>
</Sub-SubNode1 attribute1='values'>
</SubNode1>
</MainNode>
An XML file can have several nodes of type SubNode1, all of them are called the same; However, I'm only interested in what Node-Of-Interest contains, especially if the Attribute1 attribute has a specific value, I want the value of the parent attribute in the Sub-SubNode1 attribute.
I tried using the provided xml.el functions xml-parse-region, xml-get-attributesand xml-get-childrento give me the structure as shown below:
((SubNode1 ((attribute1 . "values")) "
" (Sub-SubNode1 ((attribute1 . "values")) "
" (Node-Of-Interest nil "
" (Attribute1 ((value . "value1"))) "
" (Attribute2 ((value . "value2"))) "
") "
") "
")
(SubNode1 ((attribute1 . "values")) "
" (Sub-SubNode1 ((attribute1 . "values"))) "
"))
Now my problem is: how to go through this list to find the values that I would like?
Just a base tree:
(setq tree
'((MainNode ((attribute1 . "values")
(attribute2 . "values"))
" " (SubNode1 ((attribute1 . "values"))
" " (Sub-SubNode1 ((attribute1 . "values"))
" "
(Node-Of-Interest
nil
" "
(Attribute1 ((value . "value1")))
" "
(Attribute2 ((value . "value2")))
" ")
" ")
" ")
" " (SubNode1 ((attribute1 . "values"))
" " (Sub-SubNode1 ((attribute1 . "values")))
" ")
" ")))
(defun my-recurse (lst fun)
(when (consp lst)
(append (and (funcall fun lst) (list lst))
(my-recurse (car lst) fun)
(my-recurse (cdr lst) fun))))
(require 'cl-lib)
(my-recurse
tree
(lambda (x)
(and (listp x) (symbolp (car x)) (listp (cdr x))
(cl-find-if
(lambda (y)
(and (consp y) (eq (car y) 'Node-Of-Interest)))
x))))
;; =>
;; ((Sub-SubNode1
;; ((attribute1 . "values"))
;; " " (Node-Of-Interest
;; nil " "
;; (Attribute1 ((value . "value1")))
;; " "
;; (Attribute2 ((value . "value2")))
;; " ")
;; " "))
Btw, XML Emacs.