简体   繁体   中英

python xml element.firstChild doesn't return Element

I would like o do something like this:

    simpleType = el.firstChild
    if simpleType:
        print simpleType.getAttribute("base")

where el is Element. When I try to run it, I get error:

AttributeError: Text instance has no attribute 'getAttribute'

I am assuming that first child is returning a Node. How can I get an Element instead of this? Here is wider context:

def printTypes(typeName, DOMTree):

elements = DOMTree.getElementsByTagName("xsd:simpleType")
simpleType = None
for el in elements:
    if el.getAttribute("name") == typeName :
        simpleType = el.firstChild
        if simpleType:
            print simpleType.getAttribute("base")
        break

And an exaple ox the xml:

<xsd:element name="VictimInformation" type="VictimInformationType"/>
<xsd:simpleType name="VictimInformationType">
    <xsd:restriction base="xsd:string"/>
</xsd:simpleType>

Check this:

for c in el.childNodes:
    if c.nodeType != node.TEXT_NODE:

My psychic powers tell me the input is like

<el>text<simpleType base="val" /></el>

Therefore, the first child element of <el> is the Text text (maybe even just spaces). You can just iterate over the childNodes property like this:

for c in el.childNodes:
    if c.tagName == 'simpleType':
        print c.getAttribute('base')
        break

As a side effect, this will make your application compatible with future/third-party extensions of the format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM