0

Not sure if this is going to be a duplicate question..I have tried to find a related answer but not quite found it..here I go..

Here is what I have in XML format data

<item>
<title>level red</title>
<link>something</link>
<item>

<item>
<title>level green</title>
<link>something</link>
<item>

<item>
<title>level yellow</title>
<link>something</link>
<item>

<item>
<title>level red</title>
<link>something</link>
<item>

<item>
<title>level yellow</title>
<link>something</link>
<item>

<item>
<title>level red</title>
<link>something</link>
<item>

<item>
<title>level green</title>
<link>something</link>
<item>

<item>
<title>level black</title>
<link>something</link>
<item>

My aim is to sort this data in a where level red first and level green and level yellow comes in the xml list and the rest of level stays whatever..

My question is how do I approach this with Python?

I know I might have to use

dom =  xml.dom.minidom.parseString(stripTags(data))
items = dom.getElementsByTagName('item')

item.getElementsByTagName("title")[0].childNodes
item.getElementsByTagName("link")[0].childNodes

I have also seen code like this to sort in order

sorted_b = []
for i in a:
    for j in b:
        if j.id == i:
            sorted_b.append(j)
            break

My problem is how do I put the code together and later how i sort the data in my given order of color priority?

Any suggestion or direction is appreciated

1 Answer 1

1

The Python sorted() function might come in handy:

https://wiki.python.org/moin/HowTo/Sorting

especially with the key=... argument. Try something like

def getItemLevel(item):
  return item.getElementsByTagName("title")[0].data

newlist = sorted(itemlist, key=getItemLevel)
Sign up to request clarification or add additional context in comments.

1 Comment

I kind of understand little bit but could not figure out how I specify the range such as Red, Green, Yellow..whichever exist will follow the order...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.