How to find if there are empty attributes in XML?

Viewed 24

Having a XML like this one (located in /home/user/):

<?xml version="1.0" ?>
<DataClient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cnmc="http://www.example.com/Tipos_DataClient" xmlns="http://www.example.com/DataClient">
   <PersonalData Operation="3" Date="2022-09-06">
      <ExtendedData>
         <Person Code="XXX" OtherCode="Y12354"/>
      </ExtendedData>
      <Home Type="Street" Num="10" Code="12003" Poblation="Imaginary street"/>
   </PersonalData>
</DataClient>

How could I identify if the "Num" attribute is empty? And then generate a list of all those elements that have the "Num" empty...

I tried to count all those with "None" as value, but it always returns 0:

#! /usr/bin/python3

import xml.etree.ElementTree as ET
tree = ET.parse('/home/user/file.xml')
root = tree.getroot()
b = None
a = sum(1 for s in root.findall('./DataClient/PersonalData/ExtendedData/Num') if s.b)

print (a)
1 Answers

Since Python's etree API maps attributes to dictionaries, consider dict.get to check for specific attribute. Also, you need to use namespaces argument of findall since XML contains a default namespace.

import xml.etree.ElementTree as ET 

tree = ET.parse('/home/user/file.xml')

nmsp = {"doc": "http://www.example.com/DataClient"}
xpath = "./doc:DataClient/doc:PersonalData/doc:Home"

a = sum(1 for node in tree.findall(xpath, nmsp) if node.attrib.get("Num") is None) 
Related