Python XML xpath-如果找不到元素,则传递值
我目前正在尝试解析一个XML文件,下面的代码运行良好,只有一个问题。在我创建的全名列表中,这是唯一一个不总是出现在每个子树中的标记,即Python XML xpath-如果找不到元素,则传递值,python,xml,pandas,xpath,Python,Xml,Pandas,Xpath,我目前正在尝试解析一个XML文件,下面的代码运行良好,只有一个问题。在我创建的全名列表中,这是唯一一个不总是出现在每个子树中的标记,即用户名,配置文件,&身份验证类型都返回30项,而全名返回27项 因此,当我试图创建数据帧时,我得到一个错误,因为列表的长度不同 xmltree = ET.parse(xml) namespaces = {'ns5':'urn:swift:saa:xsd:operator', 'profile':'urn:swift:saa:xsd:op
用户名
,配置文件
,&身份验证
类型都返回30项,而全名
返回27项
因此,当我试图创建数据帧时,我得到一个错误,因为列表的长度不同
xmltree = ET.parse(xml)
namespaces = {'ns5':'urn:swift:saa:xsd:operator',
'profile':'urn:swift:saa:xsd:operatorprofile'
}
user_names = xmltree.xpath('//ns5:Identifier/ns5:Name/text()', namespaces=namespaces)
full_names = xmltree.xpath('//ns5:Description/text()', namespaces=namespaces)
profiles = xmltree.xpath('//profile:Name/text()', namespaces=namespaces)
authentication_types = xmltree.xpath('//ns5:AuthenticationType/text()', namespaces=namespaces)
xml = pd.DataFrame({'User_Name': user_names, 'Full_Name': full_names,
'Profile': profiles, 'Authentication_Type': authentication_types})
是否有一种方法可以在全名列中使用空值(或空白)创建dataframe
试试这个,没有在你的代码上测试,因为没有完全复制
full_names = xmltree.xpath('//ns5:Description/text()', namespaces=namespaces) if xmltree.xpath('//ns5:Description/text()', namespaces=namespaces) else ""
或者在多行中使用相同的代码
full_names = xmltree.xpath('//ns5:Description/text()', namespaces=namespaces)
if not full_name:
full_names = ""
昨晚我在想这个问题,意识到我需要识别父标记并在其中循环寻找子标记。改变了我的方法,现在正按照我想要的方式工作
对于任何面临这个问题的人来说,这里是我使用的修复方法
root = xmltree.getroot()
user_names = []
full_names = []
profiles = []
authentication_types = []
for i in root.findall('.//{urn:swift:saa:xsd:impex:operator}Operator'):
usernames = i.find('.//{urn:swift:saa:xsd:operator}Name')
usernames2 = "" if usernames is None else usernames.text
user_names.append(usernames2)
fullnames = i.find('{urn:swift:saa:xsd:operator}Description')
fullnames2 = "" if fullnames is None else fullnames.text
full_names.append(fullnames2)
user_profiles = i.find('.//{urn:swift:saa:xsd:operatorprofile}Name')
user_profiles2 = "" if user_profiles is None else user_profiles.text
profiles.append(user_profiles2)
authenications = i.find('{urn:swift:saa:xsd:operator}AuthenticationType')
authenications2 = "" if authenications is None else authenications.text
authentication_types.append(authenications2)
xml = pd.DataFrame({'User_Name': user_names,
'Full_Name': full_names,
'Profile': profiles,
'Authentication_Type': authentication_types})
感谢您的响应,但不幸的是,这不起作用,因为“if xmltree.xpath('//ns5:Description/text()',namespaces=namespaces)”将返回True,因为列表中可能有一些元素。另外,我认为另一个问题是xpath将只查找匹配的条目,它不理解在某些情况下缺少元素,因此我可能需要找出如何循环父标记并在该标记内搜索。