原来的帖子似乎太模糊了,所以我缩小了这篇文章的重点。我有一个XML文件,我想从中提取特定分支的值,我很难理解如何有效地导航XML路径。考虑下面的XML文件。有几个<mi>
分支。我想存储某些分支的<r>
值,但不存储其他分支的值。在这个例子中,我想要counter1和counter3的<r>
值,而不是counter2。在
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="Data.xsl" ?>
<!DOCTYPE mdc SYSTEM "Data.dtd">
<mdc xmlns:HTML="http://www.w3.org/TR/REC-xml">
<mfh>
<vn>TEST</vn>
<cbt>20140126234500.0+0000</cbt>
</mfh>
<mi>
<mts>20140126235000.0+0000</mts>
<mt>counter1</mt>
<mv>
<moid>DEFAULT</moid>
<r>58</r>
</mv>
</mi>
<mi>
<mts>20140126235000.0+0000</mts>
<mt>counter2</mt>
<mv>
<moid>DEFAULT</moid>
<r>100</r>
</mv>
</mi>
<mi>
<mts>20140126235000.0+0000</mts>
<mt>counter3</mt>
<mv>
<moid>DEFAULT</moid>
<r>7</r>
</mv>
</mi>
</mdc>
在此基础上,我将构建一个包含以下内容的元组:
('20140162234500.0+0000',58,7)
其中2014016234500.0+0000取自<cbt>
,58取自<mi>
元素的<r>
值,7取自具有<mt>counter3</mt>
的{
我想使用xml.etree.cElementTree
,因为它似乎是标准的,而且对于我的目的来说应该是非常有用的。但是我在导航树和提取我需要的值方面遇到了困难。下面是我尝试过的一些方法。在
从伪代码的角度来看,我想做的是:
find the <cbt> value and store it in the first position of the tuple.
find the <mi> element where <mt>counter1</mt> exists and store the <r> value in the second position of the tuple.
find the <mi> element where <mt>counter3</mt> exists and store the <r> value in the third position of the tuple.
我不清楚何时使用element.iter()
或{XPath
,或者无法提取我需要的信息,我也不太幸运。在
谢谢, 生锈的
开始于:
现在,
^{pr2}$tree
有了xml树,xml_dict
将是您试图获得结果的字典。在计数器位于
^{3}$'mi'
:此时,
xml_dict
是:一些缩短,尽管可能不可读:
for elem in tree.findall('mi'):
循环中的代码可以是:或者更进一步地说,构建
xml_dict
只需两行,计数器在前面,cbt
之后:编辑:
From the docs,^{} 只查找带有标记的元素,这些元素是当前元素的直接子元素。在
find()
只找到第一个直接子级。在^{} 递归地遍历所有元素。在
相关问题 更多 >
编程相关推荐