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?
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.
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)
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.