Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

python - How can I check the existence of attributes and tags in XML before parsing?

I'm parsing an XML file via Element Tree in python and and writing the content to a cpp file.

The content of children tags will be variant for different tags. For example first event tag has party tag as child but second event tag doesn't have.

-->How can I check whether a tag exists or not before parsing?

-->Children has value attribute in 1st event tag but not in second. How can I check whether an attribute exists or not before taking it's value.

--> Currently my code throws an error for non existing party tag and sets a "None" attribute value for the second children tag.

<main>
  <event>
    <party>Big</party>
    <children type="me" value="3"/>
  </event>

  <event>
    <children type="me"/>
  </event>

</main>

Code:

import xml.etree.ElementTree as ET
tree = ET.parse('party.xml')
root = tree.getroot()
for event in root.findall('event'):
    parties = event.find('party').text
    children = event.get('value')

I want to check the tags and then take their values.

question from:https://stackoverflow.com/questions/15568126/how-can-i-check-the-existence-of-attributes-and-tags-in-xml-before-parsing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If a tag doesn't exist, .find() indeed returns None. Simply test for that value:

for event in root.findall('event'):
    party = event.find('party')
    if party is None:
        continue
    parties = party.text
    children = event.get('value')

You already use .get() on event to test for the value the attribute; it returns None as well if the attribute does not exist.

Attributes are stored in the .attrib dictionary, so you can use standard Python techniques to test for the attribute explicitly too:

if 'value' in event.attrib:
    # value attribute is present.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...