使用多个循环和ET解析Python中的XML
我正在使用Python2.7编写一个脚本,该脚本与以XML格式返回的防火墙API对话。我希望它能找到满足某些条件的所有规则,但我在解析XML时遇到了困难 由于我的环境被锁定,我无法使用外部模块。所以我使用urllib2和ElementTree XML(实际的XML是海量的) 此时,我的想法是使用这个“规则”列表来指定“/result/security/rules/entry/rules[x]”或类似的XPATH(可能必须使用@name)。然后使用我要查找的If条件搜索源节点和目标节点。这样,我就可以将规则名称与源和目标关联起来 然后我意识到可能有一个更简单的方法,我想我应该在这里问一下使用多个循环和ET解析Python中的XML,python,xml,xpath,urllib2,elementtree,Python,Xml,Xpath,Urllib2,Elementtree,我正在使用Python2.7编写一个脚本,该脚本与以XML格式返回的防火墙API对话。我希望它能找到满足某些条件的所有规则,但我在解析XML时遇到了困难 由于我的环境被锁定,我无法使用外部模块。所以我使用urllib2和ElementTree XML(实际的XML是海量的) 此时,我的想法是使用这个“规则”列表来指定“/result/security/rules/entry/rules[x]”或类似的XPATH(可能必须使用@name)。然后使用我要查找的If条件搜索源节点和目标节点。这样,我就
谢谢你我能想出来 我缺少的是在XML搜索中使用“[@name='VARIABLE']”对查询进行索引的方法
import urllib2
import xml.etree.ElementTree as ET
url = "https://MyFirewall/api"
response = urllib2.urlopen(url)
html = response.read()
contents = ET.fromstring(html)
rules = []
for item in contents.findall('./result/security/rules/entry'):
rules.append(item.attrib['name'])
for rule in rules:
for item in contents.findall(".//*[@name='" + rule + "']/source/member"): #This line is what I was missing
source = item.text
for item in contents.findall(".//*[@name='" + rule + "']/destination/member"): #This line is what I was missing
destination = item.text
if ("any" in source) or ("any" in destination):
print "Rule " + rule + "in Device Group : " + device + "contains an ANY"
#do stuff
import urllib2
import xml.etree.ElementTree as ET
url = "https://MyFirewall/api"
response = urllib2.urlopen(url)
html = response.read()
contents = ET.fromstring(html)
#Get the list of rules
rules = []
for item in contents.findall('./result/security/rules/entry'):
rules.append(item.attrib['name'])
import urllib2
import xml.etree.ElementTree as ET
url = "https://MyFirewall/api"
response = urllib2.urlopen(url)
html = response.read()
contents = ET.fromstring(html)
rules = []
for item in contents.findall('./result/security/rules/entry'):
rules.append(item.attrib['name'])
for rule in rules:
for item in contents.findall(".//*[@name='" + rule + "']/source/member"): #This line is what I was missing
source = item.text
for item in contents.findall(".//*[@name='" + rule + "']/destination/member"): #This line is what I was missing
destination = item.text
if ("any" in source) or ("any" in destination):
print "Rule " + rule + "in Device Group : " + device + "contains an ANY"
#do stuff