Search code examples
pythonpython-3.xxmlattributes

why can't I get xml tag attributes


so I was trying to code a test for reading xml files but for some reason I can't get the tag attributes please help python

from xml.dom.minidom import *
playerxml = parse('C:/Users/dimit/AppData/Local/Programs/Python/Python312/projects/save test.xml')
u1 = playerxml.firstChild
print(u1.firstChild.tagName)
print(u1.firstChild.tagName.getAttribute("up"))
print(u1.firstChild.tagName.getAttribute("down"))
print(u1.firstChild.tagName.getAttribute("left"))
print(u1.firstChild.tagName.getAttribute("right"))

xml

<user1>
</controls up='w' down='s' left='a' right='d'>
</name name='dimitri'>
</user1>

I tried to look at the error messages for help but I couldn't understand it mainly because it was printing out module code


Solution

    1. test.xml:
    <user1>
        </controls up='w' down='s' left='a' right='d'>
        </name name='dimitri'>
    </user1>
    
    1. main.py:

    .

    from xml.dom.minidom import parse
    
    playerxml = parse('test.xml')
    u1 = playerxml.firstChild
    controls_tag = u1.getElementsByTagName('controls')[0]  
    name_tag = u1.getElementsByTagName('name')[0]
    
    
    
    print("Controls attributes:")
    print("Up:", controls_tag.getAttribute("up"))
    print("Down:", controls_tag.getAttribute("down"))
    print("Left:", controls_tag.getAttribute("left"))
    print("Right:", controls_tag.getAttribute("right"))
    
    print("\nName attribute:")
    print("Name:", name_tag.getAttribute("name"))
    

    Output:

    Controls attributes:
    Up: w
    Down: s
    Left: a
    Right: d
    
    Name attribute:
    Name: dimitri