解决方案中的问题是“元素数据提取”没有正确完成。您在问题中提到的xml嵌套在几个层中。这就是为什么我们需要递归地读取和提取数据。在这种情况下,下面的解决方案应该能满足您的需要。尽管我鼓励你看一下this article和{a2}以获得更清晰的理解。在

方法:1import numpy as np

import pandas as pd

#import os

import xml.etree.ElementTree as ET

def xml2df(xml_source, df_cols, source_is_file = False, show_progress=True):

"""Parse the input XML source and store the result in a pandas

DataFrame with the given columns.

For xml_source = xml_file, Set: source_is_file = True

For xml_source = xml_string, Set: source_is_file = False

Child 1 Text

Child 2 Text

Child 3 Text

Note that for an xml structure as shown above, the attribute information of

element tag can be accessed by list(element). Any text associated with tag can be accessed

as element.text and the name of the tag itself can be accessed with

element.tag.

"""

if source_is_file:

xtree = ET.parse(xml_source) # xml_source = xml_file

xroot = xtree.getroot()

else:

xroot = ET.fromstring(xml_source) # xml_source = xml_string

consolidator_dict = dict()

default_instance_dict = {label: None for label in df_cols}

def get_children_info(children, instance_dict):

# We avoid using element.getchildren() as it is deprecated.

# Instead use list(element) to get a list of attributes.

for child in children:

#print(child)

#print(child.tag)

#print(child.items())

#print(child.getchildren()) # deprecated method

#print(list(child))

if len(list(child))>0:

instance_dict = get_children_info(list(child),

instance_dict)

if len(list(child.keys()))>0:

items = child.items()

instance_dict.update({key: value for (key, value) in items})

#print(child.keys())

instance_dict.update({child.tag: child.text})

return instance_dict

# Loop over all instances

for instance in list(xroot):

instance_dict = default_instance_dict.copy()

ikey, ivalue = instance.items()[0] # The first attribute is "ID"

instance_dict.update({ikey: ivalue})

if show_progress:

print('{}: {}={}'.format(instance.tag, ikey, ivalue))

# Loop inside every instance

instance_dict = get_children_info(list(instance),

instance_dict)

#consolidator_dict.update({ivalue: instance_dict.copy()})

consolidator_dict[ivalue] = instance_dict.copy()

df = pd.DataFrame(consolidator_dict).T

df = df[df_cols]

return df

运行以下命令以生成所需的输出。在

^{pr2}$

方法:2

{{cd2>你可以转换。运行以下命令以获得所需的输出。在pip install -U xmltodictSolutiondef read_recursively(x, instance_dict):

#print(x)

txt = ''

for key in x.keys():

k = key.replace("@","")

if k in df_cols:

if isinstance(x.get(key), dict):

instance_dict, txt = read_recursively(x.get(key), instance_dict)

#else:

instance_dict.update({k: x.get(key)})

#print('{}: {}'.format(k, x.get(key)))

else:

#print('else: {}: {}'.format(k, x.get(key)))

# dig deeper if value is another dict

if isinstance(x.get(key), dict):

instance_dict, txt = read_recursively(x.get(key), instance_dict)

# add simple text associated with element

if k=='#text':

txt = x.get(key)

# update text to corresponding parent element

if (k!='#text') and (txt!=''):

instance_dict.update({k: txt})

return (instance_dict, txt)

您需要上面给出的函数read_recursively()。现在运行以下命令。在import xmltodict, json

o = xmltodict.parse(xml_string) # INPUT: XML_STRING

#print(json.dumps(o)) # uncomment to see xml to json converted string

consolidated_dict = dict()

oi = o['Instances']['Instance']

for x in oi:

instance_dict = dict()

instance_dict, _ = read_recursively(x, instance_dict)

consolidated_dict.update({x.get("@ID"): instance_dict.copy()})

df = pd.DataFrame(consolidated_dict).T

df = df[df_cols]

df

python 处理xml pandas_在python中解析xml到pandas数据帧相关推荐

  1. Android解析xml的方法,Android中解析XML格式数据的方法

    XML介绍:Extensible Markup Language,即可扩展标记语言 一.概述 Android中解析XML格式数据大致有三种方法: SAX DOM PULL 二.详解 2.1 SAX S ...

  2. Android中解析XML

    Android中解析XML 转载于:https://www.cnblogs.com/zhujiabin/p/5868993.html

  3. java dom xml 换行,dom4j解析xml文件_用DOM解析XML文件,怎么才能让解析出来的文本不用换行_dom解析xml文件...

    网友求助:dom4j解析xml文件_用DOM解析XML文件,怎么才能让解析出来的文本不用换行_dom解析xml文件 问题importjava.text.SimpleDateFormat; import ...

  4. 如何在Python中解析XML?

    我在包含xml的数据库中有很多行,并且我正在尝试编写一个Python脚本,该脚本将遍历这些行并计算出现特定节点属性的实例数量. 例如,我的树看起来像: <foo><bar>&l ...

  5. python输出价目表-Python:使用基于事件驱动的SAX解析XML

    SAX的特点: 是基于事件的 API 在一个比 DOM 低的级别上操作 为您提供比 DOM 更多的控制 几乎总是比 DOM 更有效率 但不幸的是,需要比 DOM 更多的工作 基于对象和基于事件的接口 ...

  6. java中解析xml解读,java解析xml(JDOM)

    下面通过一个简单的例子说明一下怎么用JDOM这一适合Java程序员习惯的工具包来解析XML文档. 为了简单,我用了如下XML作为要解析的XML文件: rjzjh 60.0 够简单的吧,但它对于我们关心 ...

  7. Java 中解析 xml 格式字符串的数据

    解析 xml 格式中的字符串数据 相信有很多小伙伴经历过接口返回的数据是在一段 xml 字符串格式的数据里,那么我们可用什么最快最便捷的方法取到里面的数据勒? 下面这里是一个xml 格式的是实例 这里 ...

  8. php xml相关函数方法,php中对xml读取的相关函数的介绍一

    对象 XML解析函数 描述 元素 xml_set_element_handler() 元素的开始和结束 字符数据 xml_set_character_data_handler() 字符数据的开始 外部 ...

  9. XML简介和使用AFNetworking解析XML案例

    01-XML简介 曾经最流行的出身名门, W3C主推,IBM & 微软 可扩展"标记"语言 XML键值对  阅读方便,美观大方 <标记></标记> ...

最新文章

  1. 深入理解计算机系统(1.3)---金字塔形的存储设备、操作系统的抽象概念
  2. PHP验证码无法显示的原因
  3. js确保正确this的几种写法
  4. php 生成wsdl工具,php中使用zendstudio 12为soapserver生成wsdl文件
  5. 计算机科学申请文书,美国留学:看牛人怎么写申请计算机CS专业的文书
  6. 头文件和实现文件的关系
  7. TCP协议的滑动窗口协议以及流量控制
  8. iOS在照片上添加水印
  9. 十六进制计算器 android,十六进制计算器
  10. cruise软件模型,cruise增程混动仿真模型,功率跟随控制策略,Cruise混动仿真模型,串联混动汽车动力性经济性仿真
  11. C#EXE 文件中 嵌入dll文件
  12. poi根据Word模板导出Word文件,Word模板
  13. writeUP-[第五空间2019 决赛]PWN5(待进一步完善待研究内容)
  14. 实例003 输出名言
  15. JAVA已知圆心经纬度和半径求圆周点的经纬度
  16. 最新手机号验证正则表达式(电信、移动、广电号段)
  17. 《智能制造》总结报告
  18. linux搭建泰拉瑞亚(Terraria)服务器
  19. LeetCode 每日一题 3. 无重复字符的最长子串
  20. cocos creator 3D学习(六)光照+阴影

热门文章

  1. solrcloud 7.5在k8s上的部署安装和使用教程
  2. 字符串函数rpartition与partition
  3. hashCode 一致性hash 算法
  4. transform:rotate在手机上显示有锯齿的解决方案
  5. Java零基础系列003——变量
  6. 扩展 delphi 泛型 以实现类似lambda功能 , C#中的any count first last 等扩展方法
  7. python脚本性能分析
  8. [转载] python sorted 使用cmp函数时候注意cmp需要传入两个参数,传入两个参数机制的分析
  9. [转载] python程序所需的图片通过base64编码成字符串放在代码中
  10. [转载] [Python] np.ones_like(ndarray)和np.zeros_like(ndarray)