[英]Python parsing the Xml with namespace
需要解析的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,'CLIAggregation')(SM_HOUR_FORMAT,'24_HR')(MCNRecordsOrder,'LIFO')
您可以執行以下幾項操作來確保找到正確的文件-
我看不到以下行中提到的.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')
這應該工作。 讓我知道是否有幫助。 :)
嘗試這個:
導入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)
這將給您想要的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.