gpt4 book ai didi

xml - Elisp 解析 XML,然后搜索特定值

转载 作者:数据小太阳 更新时间:2023-10-29 02:10:50 24 4
gpt4 key购买 nike

我有一个 XML 文件,其中包含多个嵌套组,例如

<?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>

XML 文件可能有多个 SubNode1 类型的节点,所有节点的名称都相同;但是,我只对包含感兴趣节点的内容感兴趣,特别是如果属性 Attribute1 具有特定值,我想要 Sub-SubNode1 attribute1 中父属性的值。

我尝试使用提供的 xml.el 函数xml-parse-regionxml-get-attributesxml-get-children 给我一个结构如下:

((SubNode1 ((attribute1 . "values")) "
" (Sub-SubNode1 ((attribute1 . "values")) "
" (Node-Of-Interest nil "
" (Attribute1 ((value . "value1"))) "
" (Attribute2 ((value . "value2"))) "
") "
") "
")
(SubNode1 ((attribute1 . "values")) "
" (Sub-SubNode1 ((attribute1 . "values"))) "
"))

我现在的问题是,如何遍历此列表以找到我想要的值?

最佳答案

只是一个基本的树行走:

(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")))
;; " ")
;; " "))

顺便说一句,根据 Emacs 验证程序,您的 XML 已损坏。

关于xml - Elisp 解析 XML,然后搜索特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22150693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com