我正在尝试在xml中一起打印属性和元素文本。
这是我拥有的以下xml内容:
<nodes count="10" totalCount="14050">
<node foreignId="XX-WTRFGORXNWOAFG" foreignSource="XX" label="ABERTOXK01" id="10314" type="A">
<assetRecord>
<category>Unspecified</category>
<city>Boston</city>
<id>1795234</id>
<lastModifiedBy/>
<lastModifiedDate>2016-05-22</lastModifiedDate>
<manufacturer>Cisco Systems</manufacturer>
<modelNumber>ACE 4710</modelNumber>
<node>23456</node>
<operatingSystem>#NO_VALUE</operatingSystem>
<region>Eastern & North America</region>
<serialNumber>XX</serialNumber>
</assetRecord>
<categories id="16" name="Class 1"/>
<categories id="812" name="Site_XX"/>
<categories id="69" name="Wireless"/>
<categories id="14" name="10min_collect"/>
<createTime>2016-09-21</createTime>
<labelSource>U</labelSource>
<lastCapsdPoll>2018-08-08</lastCapsdPoll>
<sysContact>ABERTOXK01</sysContact>
<sysDescription>ACE 4710 Application Control Engine Appliance</sysDescription>
<sysLocation>Boston</sysLocation>
<sysName>ABERTOXK01</sysName>
<sysObjectId>ERTYDDS</sysObjectId>
</node>
</nodes>
我能够从<node> label =
这样的属性中提取数据,甚至可以从<manufacturer>Cisco Systems</manufacturer>
这样的元素中提取数据。但是,我无法在我的代码中一起打印它们。我想我遗漏了非常明显的东西。请帮忙!
这是我到目前为止尝试过的:
import requests
import urllib3
import base64
urllib3.disable_warnings()
from xml.etree import ElementTree as ET
decoderuser = base64.urlsafe_b64decode(b'someusername')
username = decoderuser.decode("utf-8")
decoderpassword = base64.urlsafe_b64decode(b'somepassword')
password = decoderpassword.decode("utf-8")
print("Connection to OpenNMS is successful!")
response = requests.get("https://server/opennms/rest/nodes?limit=10", verify=False, auth=(username, password))
root = ET.fromstring(response.content)
items = root.findall('node/*')
for item in items:
for child in root.iterfind('node'):
#print(child.tag, child.attrib['label'])
while item.find('city') is str:
try:
print((item.find('city')).text, (item.find('manufacturer')).text, child.attrib['label'])
except: continue
我有10个类似的子节点,如果增加搜索范围,它们可以更多。另外,某些节点没有像<city>sometext</city>
这样的元素。我在上面尝试的代码不会打印我需要的任何属性或元素。如果我不放置 while循环,它将打印所有属性以及元素,但是我不希望它遍历没有<city>sometext</city>
和反之亦然。
非常感谢!