簡體   English   中英

Python將XML輸出與列表進行比較

[英]Python comparing XML output to a list

我有一個看起來像這樣的XML:

<Import>
  <spId>1234</spId>
  <GroupFlag>false</GroupFlag>
</Import>

我想提取spId的值並將其與列表進行比較,我有以下腳本:

import xml.etree.ElementTree as ET
xml_file = "c:/somefile.xml"

sp_id_list = ['1234']
tree = ET.parse(xml_file)
root = tree.getroot()

for sp_id in root.findall('./spId'):
  if sp_id.text in sp_id_list:
    print sp_id.text

這不適用於spId(數字),但適用於將GroupFlag(字符串)與列表進行比較。 為什么會發生這種情況,如何解決這個問題?

很抱歉這個愚蠢的問題,我對此不滿意。

如果此處發布的XML示例作為輸入XML文件給出,則您的代碼示例將正常工作。

但是,您想查找所有元素。 因此,我假設您的真實文檔中有許多<Import>項目。 如果項目列表沒有被某些父標記包裝,則它不是有效的XML。 在這種情況下,您將擁有xml.etree.ElementTree.ParseError

因此,我假設在您的真實文檔中, <Import>不是根元素,而<Import>元素在文檔中更深處,例如

<Parent>
  <Import>
    <spId>1234</spId>
    <GroupFlag>false</GroupFlag>
  </Import>
  <Import>
    <spId>1234</spId>
    <GroupFlag>false</GroupFlag>
  </Import>
</Parent>

在那種情況下,搜索模式'./spId'找不到那些標記,因為該模式僅匹配根元素的直接子代。 因此,您可以使用XPath匹配標簽,在所有級別以下甚至更好地指向從根到spId所在級別的直接路徑:

# all subelements, on all levels beneath the current element
root.findall('.//spId')

# all spId elements directly in Import tags that are directly
# beneath the root element (as in the above XML example)
root.findall('./Import/spId'):

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM