简体   繁体   中英

Python parsing the Xml with namespace

Xml which need to be parsed "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>

This is Python script I am using to Parse the XMl to get "param" and "value" tag.But findall is return empty.

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')

Here are a few things that you can do to make sure that you're hitting up the right file-

I don't see the name of the .XML file mentioned in this following line -

for cos in root.findall('./config/sys/app/Feature'):

Make sure to enter the name of your file in this code like this-

for cos in root.findall('./config/sys/app/Feature/cos1.XML'):

If it still does not work, try to define a proper path to the file-

import os
current_path = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(current_path+'/config/sys/app/Feature/cos1.XML')

This should work. Let me know if it helps. :)

Try this:

import xml.etree.ElementTree as ET import sys

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)

This will give you desired results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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