Home > database >  How to check if particular tag name equals a value and return the entire data inside the tag from XM
How to check if particular tag name equals a value and return the entire data inside the tag from XM

Time:02-04

I have a xml with the following structure:

<?xml version="1.0" ?>
<Parameters>
  <Test name="Login" browser="chrome">
    <TestParamerer version="1.2" timeout="480"/>
  </Test>
   <Test name="Logout" browser="chrome">
    <TestParamerer version="2.3" timeout="480"/>
    <Arguments name="EF" version="2.2"/>
  </Test>
</<Parameters>

I need to retrieve Test with name="Login" and to return the entire value in JSON format inside the Test tag. I am new to Python and so any help is appreciated.

CodePudding user response:

You can use etree, json and xmltodict

from lxml import etree
import json
import xmltodict

xml = """<?xml version="1.0" ?>
<Parameters>
  <Test name="Login" browser="chrome">
    <TestParamerer version="1.2" timeout="480"/>
  </Test>
   <Test name="Logout" browser="chrome">
    <TestParamerer version="2.3" timeout="480"/>
    <Arguments name="EF" version="2.2"/>
  </Test>
</Parameters>"""

tree = etree.fromstring(xml)
login = tree.findall('.//Test[@name="Login"]')
# [<Element Test at 0x29bc1ac7480>] (in this case 1 element). 
dict_from_xml = xmltodict.parse(etree.tostring(login[0]))
'''
OrderedDict([('Test',
              OrderedDict([('@name', 'Login'),
                           ('@browser', 'chrome'),
                           ('TestParamerer',
                            OrderedDict([('@version', '1.2'),
                                         ('@timeout', '480')]))]))])
'''
# And now to json':
js = json.dumps(dict_from_xml, indent=2)

print(js)
'''
{
  "Test": {
    "@name": "Login",
    "@browser": "chrome",
    "TestParamerer": {
      "@version": "1.2",
      "@timeout": "480"
    }
  }
}
'''
  •  Tags:  
  • Related