繁体   English   中英

Python使用名称空间解析Xml

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM