2

I'm learning Python and need your help.

I'm trying to parse an XML file to TSV using minidom. In that XML file I have multiple tags with same name. I want concatenate them and return in a single delimited string. Can anyone help me.

XML:

<items>
<item_name>iPhone</item_name>
<category>Smart Phone</category>
<category>Electronics</category>
<category>Communications</category>
</items>

Desired output:

iPhone    Smart Phone, Electronics, Communications

Python Code:

dom = parseString(data)

xmlTag = dom.getElementsByTagName('items')
for node in xmlTag:
    item = node.getElementsByTagName('item')[0]
    cat = node.getElementsByTagBane('category')
print("%s\t%s" % item, cat)
2
  • What is your problem? Also, I suppose you mispelled tagName for tagBane? Commented Apr 16, 2015 at 23:06
  • Is this your real code? There is a typo in node.getElementsByTagBane(). Furthermore, the selection of elements with tag name 'item' will be empty because the xml you provided simply contains no element of that name. Please correct your code. Commented Apr 16, 2015 at 23:11

1 Answer 1

1

I would suggest you the following code. I don't know if I get your problem but your code seems incomplete.

dom = parseString(data)

xmlTag = dom.getElementsByTagName('items')
for node in xmlTag:
    item = node.getElementsByTagName('item_name')[0]
    print item,
    cat = node.getElementsByTagBane('category')
    for s in cat:
        print s.childNodes[0].data,
    print ""
Sign up to request clarification or add additional context in comments.

Comments

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.