我正在尝试读取XML文件并将其转换为pandas。但是它返回空数据
以下是xml结构示例:
<Instance ID="1">
<MetaInfo StudentID ="DTSU040" TaskID="LP03_PR09.bLK.sh" DataSource="DeepTutorSummer2014"/>
<ProblemDescription>A car windshield collides with a mosquito, squashing it.</ProblemDescription>
<Question>How does this work tion?</Question>
<Answer>tthis is my best </Answer>
<Annotation Label="correct(0)|correct_but_incomplete(1)|contradictory(0)|incorrect(0)">
<AdditionalAnnotation ContextRequired="0" ExtraInfoInAnswer="0"/>
<Comments Watch="1"> The student forgot to tell the opposite force. Opposite means opposite direction, which is important here. However, one can argue that the opposite is implied. See the reference answers.</Comments>
</Annotation>
<ReferenceAnswers>
1: Since the windshield exerts a force on the mosquito, which we can call action, the mosquito exerts an equal and opposite force on the windshield, called the reaction.
</ReferenceAnswers>
</Instance>
我试过这个代码,但是它对我不起作用。它返回空的数据帧。在
^{pr2}$
几个问题:
node
调用.find
,要求存在一个子节点:current_node.find('child_of_current_node')
。但是,由于所有的节点都是根的子节点,所以不需要维护自己的子节点,所以不需要循环NoneType
,这可能是由于缺少带有find()
的节点而导致的,并阻止检索{.text
检索节点内容,否则返回<Element...
对象考虑使用ternary condition expression
a if condition else b
进行此调整,以确保变量具有值,而不管:或者,运行一个更动态的版本,使用iterator变量为内部字典赋值:
^{pr2}$或列表/听写理解:
解决方案中的问题是“元素数据提取”没有正确完成。您在问题中提到的xml嵌套在几个层中。这就是为什么我们需要递归地读取和提取数据。在这种情况下,下面的解决方案应该能满足您的需要。尽管我鼓励你看一下this article和{a2}以获得更清晰的理解。在
方法:1
运行以下命令以生成所需的输出。在
^{pr2}$方法:2
{{cd2>你可以转换。运行以下命令以获得所需的输出。在
注意:您需要安装^{} 才能使用方法2。这个方法的灵感来自@martin blech在How to convert XML to JSON in Python? [duplicate]
提出的解决方案。为制作它而向@martin-blech致敬。在
您需要上面给出的函数
read_recursively()
。现在运行以下命令。在相关问题 更多 >
编程相关推荐