0

I am trying to get specific order of XML attribute.

Given

<OKV s="*****" r="*****" a="*****" g="****" m="*****" e="****" d="****" i="****" n="****" v="1"/>

Required :

<OKV v="1" n="****" i="****" d="****" e="****" m="*****" g="****"  a="*****" r="*****" s="*****"/>

I am trying to implement in Python.

So far when I am using xml library.

import xml.etree.ElementTree as ET
tree = ET.parse('adhar.xml')

But it keeps read in that format, Please tell how to change the order. As I am reading correctly in internet explorer when opened the file, But getting reversed order while reading the file or see it in Chrome.

Chinmay Das
  • 400
  • 6
  • 18

2 Answers2

2

For this specific xml string you could use xmltodict (install with pip install xmltodict). This converts the xml data to a python dictionary. Using the following would reverse the order of the OKV entry:

import xmltodict
import collections
xml_data = '<OKV s="*****" r="*****" a="*****" g="****" m="*****" e="****" d="****" i="****" n="****" v="1"/>'
xml_data_parsed = xmltodict.parse(xml_data)
xml_data_parsed["OKV"] = collections.OrderedDict(reversed(list(xml_data_parsed["OKV"].items())))
xml_data = xmltodict.unparse(xml_data_parsed)

If the the part you want to reorder is embedded in a larger xml document you would have to select the deeper nested key to get to e.g. OKV.

Ascurion
  • 503
  • 3
  • 13
0

Try using lxml to parse the xml file. As suggested here, it might help get the attributes in the appropriate order.

Bolat
  • 369
  • 1
  • 8