我是 XML 新手,并試圖決議 Splunk 的 API 請求的輸出 - 這是請求的資料輸出:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xml" href="/static/atom.xsl"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:s="http://dev.splunk.com/ns/rest" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">
<generator build="87e2dda940d1" version="8.2.4"/>
<opensearch:totalResults>1</opensearch:totalResults>
<entry>
<link href="/services/kvstore/status/status" rel="list"/>
<content type="text/xml">
<s:dict>
<s:key name="current">
<s:dict>
<s:key name="backupRestoreStatus">Ready</s:key>
<s:key name="date">Tue Nov 1 13:07:35 2022</s:key>
<s:key name="dateSec">1667326055.814</s:key>
<s:key name="disabled">0</s:key>
</s:dict>
</s:key>
</s:dict>
</content>
</entry>
</feed>
我正在嘗試深入到以下行:
<s:key name="backupRestoreStatus">Ready</s:key>
并獲取 this 的值并將其分配給一個變數。
到目前為止,我可以運行 curl 命令并將輸出分配給一個變數。我試圖決議資料并收到沒有輸出的錯誤以接收完整輸出的副本 - 但沒有決議資訊。
這是我必須嘗試決議請求資料的ansible代碼:
- name: Parse xml for Back-up Status
community.general.xml:
path: "{{ xml_status }}"
xpath: /feed/entry/content/key[@name=backupRestoreStatus]
attribute: value
content: attribute
register: backup_stat
我得到的當前錯誤如下:
任務 [為備份狀態決議 xml] *****************************
致命:[dc1-splunk]:失敗!=> {"changed": false, "msg": "'attribute' 所需的缺少引數:值"}
uj5u.com熱心網友回復:
您在這里確實有幾個問題,在這些問題上:
- 的錯誤用法
content: attribute
,而您想要的是節點的內容,而不是其屬性之一,因此您需要content: text
- 的用法
attribute: value
,這是針對要修改的屬性值所需要的,而您的目標只是獲取一些內容 - XPath 中缺少一些節點,實際上應該是
/ns:feed/ns:entry/ns:content /s:dict/s:key[@name='current'] /s:dict/s:key[@name='backupRestoreStatus']
- 但是,也許更重要,也可能更晦澀難懂的是,您忘記了 XML命名空間這一事實
因此,關于 XML 命名空間,您必須知道,當 XML 包含命名空間定義時,您必須使用它們各自的命名空間來尋址節點。
在這里,您的命名空間是在feed
節點上定義的:
<feed
xmlns="http://www.w3.org/2005/Atom"
xmlns:s="http://dev.splunk.com/ns/rest"
xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/"
>
這個節點實際上定義了三個命名空間:
xmlns
, 默認命名空間,適用于任何沒有前綴的節點,例如<feed>
,<entry>
或<content>
xmlns:s
, 一個帶前綴的命名空間s
,比如在<s:key>
xmlns:opensearch
,一個帶有前綴的命名空間opensearch
,比如 in<opensearch:totalResults>
— 你可以把它放在一邊,因為你在要查詢的 XPath 中沒有那個命名空間前綴
namespaces
為了讓 Ansible 正確地查詢您的 XML,您必須在引數的幫助下告訴它什么是命名空間。
所以,給定兩個任務:
- community.general.xml:
path: file.xml
xpath: >-
/ns:feed/ns:entry/ns:content
/s:dict/s:key[@name='current']
/s:dict/s:key[@name='backupRestoreStatus']
content: text
namespaces:
ns: http://www.w3.org/2005/Atom
s: http://dev.splunk.com/ns/rest
register: backup_stat
- set_fact:
backup_restore_status: >-
{{ backup_stat.matches.0['{http://dev.splunk.com/ns/rest}key'] }}
你最終會得到:
backup_restore_status: Ready
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/527434.html