问题描述
我正在使用 ElementTree 和 Python 来解析 XML 文件.
I'm using ElementTree with Python to parse an XML file.
这是我试图解析的 XML 文件示例:
This is the sample of XML file I'm trying to parse:
<?xml version="1.0" encoding="UTF-8"?>
<objects fpmi.archive.type="components" framework.version="7.9.8.2018060714" fpmi.version="9.9.8.0" timestamp="Thu Sep 27 15:00:19 CEST 2018">
<arraylist len="0"/>
<c cls="com.inductiveautomation.factorypmi.application.components.template.TemplateHolder">
<c-comm>
<p2df>26.0;14.0</p2df>
<r2dd>10.0;10.0;26.0;14.0</r2dd>
<str>X123_C61023</str>
<lc>10.0;10.0;16;0;0.7058824;1.3333334</lc>
</c-comm>
<c-c m="setParameterValues" s="1;java.util.Map">
<o cls="java.util.HashMap">
<o-c m="put" s="2;O;O">
<str>tagPath</str>
<str>X123_X123_C61023</str>
</o-c>
</o>
</c-c>
<c-c m="setTemplatePath" s="1;str">
<str>[network]premium/aw1/tags/monitors</str>
</c-c>
</c>
控制台总是返回 None .
console always return None .
我的代码:
import xml.etree.ElementTree as ET
mytree = ET.parse('sample.xml')
myroot = mytree.getroot()
for x in myroot.findall('c'):
p2df=x.find('p2df')
r2dd=x.find('r2dd')
print(p2df, r2dd)
请帮忙..
推荐答案
Element.findall()
仅搜索带有标记的元素,这些元素是当前元素的直接子元素.find()
也会发生同样的情况,但 find()
返回第一个匹配项.所以首先你需要遍历到c-comm
,找到p2df
元素,并且由于objects
是根节点,你首先要遍历到c
,然后 c-comm
找到对象.见下面的片段.
Element.findall()
searches only elements with a tag which are direct children of the current element. The same is happening with find()
but find()
returns the first match. So first you need to traverse to c-comm
, to find the p2df
element, and since objects
is the root node, you first traverse to c
, then c-comm
to then find the objects. See below snippet.
import xml.etree.ElementTree as ET
mytree = ET.parse('sample.xml')
myroot = mytree.getroot()
cNode = myroot.find('c')
for x in cNode.findall('c-comm'):
p2df=x.find('p2df')
r2dd=x.find('r2dd')
print(p2df.text, r2dd.text)
您的示例 xml 格式不正确.您需要在末尾添加一个结束 </objects>
标记,以便解析器能够读取文件.
Your example xml is not well formed. You need a closing </objects>
tag at the end for the parser to be able to read the file.
这篇关于ElementTree 查找返回“无"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!