需要解析的Xml “ cos1.XML”
<config xmlns="http://tail-f.com/ns/config/1.0">
<sys xmlns="urn:XYZ:ns:yang:app:4.3.3.0">
<app>
<Feature>
<name>0</name>
<FeatureID>default</FeatureID>
<param>MaxVoiceMessageLength</param>
<value>120s</value>
</Feature>
<Feature>
<name>96</name>
<FeatureID>default</FeatureID>
<param>MCNType</param>
<value>CLIAggregation</value>
</Feature>
<Feature>
<name>97</name>
<FeatureID>default</FeatureID>
<param>SM_HOUR_FORMAT</param>
<value>24_HR</value>
</Feature>
<Feature>
<name>99</name>
<FeatureID>default</FeatureID>
<param>MCNRecordsOrder</param>
<value>LIFO</value>
</Feature>
</app>
</sys>
</config>
这是我用来解析XMl以获得“ param”和“ value”标签的Python脚本。但是findall返回空。
import xml.etree.ElementTree as ET
import sys
def modifycos():
tree = ET.parse(cos1.xml)
root = tree.getroot()
for cos in root.findall('./config/sys/app/Feature')
parameter = cos.find('param').text
parmvalue = cos.get('value')
print(parameter, parmvalue)
modifycos()
(MaxVoiceMessageLength,'120s') (MCNType,“ CLIA聚合”) (SM_HOUR_FORMAT,“ 24_HR”) (MCNRecordsOrder,'LIFO')
答案 0 :(得分:1)
您可以执行以下几项操作,以确保找到正确的文件-
我看不到以下行中提到的.XML文件的名称-
for cos in root.findall('./config/sys/app/Feature'):
请确保在此代码中输入文件名称,例如-
for cos in root.findall('./config/sys/app/Feature/cos1.XML'):
如果仍然无法正常运行,请尝试定义文件的正确路径-
import os
current_path = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(current_path+'/config/sys/app/Feature/cos1.XML')
这应该有效。让我知道是否有帮助。 :)
答案 1 :(得分:0)
尝试一下:
将xml.etree.ElementTree导入为ET 导入系统
def modifycos():
tree = ET.parse("try.xml")
root = tree.getroot()
sys = root.getchildren()[0]
app = sys.getchildren()[0]
features = app.getchildren()
for element in features:
childs = element.getchildren()
for child in childs:
if "param" in child.tag:
parameter = child.text
if "value" in child.tag:
paramvalue = child.text
print(parameter , paramvalue)
这将为您提供理想的结果。