Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally insert an attribute into a node in Python using xml.etree.ElementTree

I'm building an XML document using Python's xml.etree.ElementTree and am unable to conditionally insert an attribute into a node. Here's an example of my code:

Attr1="stamps"
Attr2="ghouls"
Attr3=""   

node = ET.SubElement(root_node, "ChildNode1",
                         Attr1=Attr1,
                         Attr2=Attr2,
                         Attr3=Attr3)

Simple enough, output is exactly as expected. However, many XML documents I've seen exclude the attribute entirely if the value is None. How do I do this? Something like:

Attr1="stamps"
Attr2="ghouls"
Attr3=""   

node = ET.SubElement(root_node, "ChildNode1",
                         Attr1=Attr1,
                         Attr2=Attr2,
                         (Attr3=Attr3 if Attr != "" else pass))

But this syntax is not supported by the library. I know I can do an if statement and copy the code over for the entire node minus the conditional value, but I do not want to duplicate code many times over. Is there a quick and easy way to do this using the ElementTree library?

like image 522
ProgrammingWithRandy Avatar asked Jan 25 '26 18:01

ProgrammingWithRandy


2 Answers

Just create the element first, and then add the attribute afterwards

node = ET.SubElement(root_node,"ChildNode1",Attr1=Attr1,Attr2=Attr2)
if Attr3 != "":
    node.attrib["Attr3"] = Attr3

The same approach can be done with Attr1 and Attr2 if you are concerned about those being empty.

ElementTree keeps all of the attributes of an element in a dictionary available in the attrib attribute of the object. The keys are the attribute names and the values are the attribute values.

like image 101
Matthew Avatar answered Jan 28 '26 08:01

Matthew


Creating a dictionary is an easy way to manipulate the keyword arguments.

attrs = {}

attrs["Attr1"] = "stamps"
attrs["Attr2"] = "ghouls"
if Attr != "":
    attrs["Attr3"] = Attr

node = ET.SubElement(root_node, "ChildNode1", **attrs)
like image 23
JakeGreen Avatar answered Jan 28 '26 07:01

JakeGreen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!