簡體   English   中英

使用 Python xml.etree.ElementTree 從 xml 文件按名稱獲取元素值

[英]Get element value by name from xml file using Python xml.etree.ElementTree

我正在使用 python-evtx 模塊來解析 Windows 事件日志。 我正在使用 883812976388.etree.ElementTree 將 output 轉換為 XML,然后嘗試解析每個條目以通過其名稱從某個鍵值中獲取值。

我有以下代碼來顯示我想要訪問的文本的不同鍵值;

import xml.etree.ElementTree as ET

tree = ET.parse('xmlfile1.txt')
root = tree.getroot()

for x in root[1]:
     print(x.tag, x.attrib, x.text)

output 看起來像這樣。

{http://schemas.microsoft.com/win/2004/08/events/event}Data {'Name': 'IpAddress'} -
{http://schemas.microsoft.com/win/2004/08/events/event}Data {'Name': 'IpPort'} -
{http://schemas.microsoft.com/win/2004/08/events/event}Data {'Name': 'ImpersonationLevel'} -
{http://schemas.microsoft.com/win/2004/08/events/event}Data {'Name': 'RestrictedAdminMode'} -
{http://schemas.microsoft.com/win/2004/08/events/event}Data {'Name': 'TargetOutboundUserName'} -
{http://schemas.microsoft.com/win/2004/08/events/event}Data {'Name': 'TargetOutboundDomainName'} -
{http://schemas.microsoft.com/win/2004/08/events/event}Data {'Name': 'VirtualAccount'} %%1843
{http://schemas.microsoft.com/win/2004/08/events/event}Data {'Name': 'TargetLinkedLogonId'} 0x0000000000000000
{http://schemas.microsoft.com/win/2004/08/events/event}Data {'Name': 'ElevatedToken'} %%1842

我想要做的是能夠獲取特定鍵值的值,例如“{http://schemas.microsoft.com/win/2004/08/events/event}Data {'Name': 'IpAddress '} -”,但無法弄清楚如何通過鍵名獲取值。

如何從 xml 883812976388.etree.ElementTree 獲取 xml output 並從特定鍵/元素獲取文本值?

我想要做的是能夠獲取特定鍵值的值,例如"{http://schemas.microsoft.com/win/2004/08/events/event}Data {'Name': 'IpAddress'} -"

使用 XPath 和命名空間 map。

import xml.etree.ElementTree as ET

ns_map = {
  'e': 'http://schemas.microsoft.com/win/2004/08/events/event'
}

tree = ET.parse('xmlfile1.txt')

# specific node
ip_address = tree.find('.//e:EventData/e:Data[@Name="IpAddress"]', ns_map)
if ip_address:
    print(ip_address.text)

# multiple nodes
for data in tree.iterfind('.//e:EventData/e:Data', ns_map):
   print(data.attrib['Name'], data.text)

http://schemas.microsoft.com/win/2004/08/events/event命名空間中的所有元素都需要 XPath 中的相應命名空間前綴(我選擇了e: ,但這是任意的,只要它解析為正確的命名空間 URI),否則將找不到它們。

暫無
暫無

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

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