【发布时间】:2019-11-29 05:50:10
【问题描述】:
我正在读取一个 XML 文件并将它的一部分写入 YAML 文件。 例如,在这个 xml 文件中,
<project>
<scm class="hudson.scm.NullSCM"/>
<assignedNode>bo1php</assignedNode>
<canRoam>false</canRoam>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers>
<hudson.triggers.TimerTrigger>
<spec>H * * * *</spec>
</hudson.triggers.TimerTrigger>
</triggers>
<concurrentBuild>false</concurrentBuild>
<builders>
我只想读取 disabled 值和 spec 值并将其写入 YAML 文件,如下所示: 预期输出:
disabled: 'false'
name: Cancellation_CMT_Tickets
triggers:
hudson.triggers.TimerTrigger:
spec: H * * * *
只有当我的结果字典是这种格式时
d = {"trigger":{"hudson.triggers.TimerTrigger": {"spec": "H * * * *"}}}
我可以将它转储到上述格式的 yaml 文件中。我当前的代码如下所示,搜索键作为运行时参数传递
import os, xml.etree.ElementTree as ET
import yaml,sys
tree = ET.parse('test.xml')
root = tree.getroot()
d = {}
def xmpparse(root,searchkey):
for child in root:
if child.tag == searchkey:
d[child.tag]=child.text
elif len(child):
xmpparse(child,searchkey)
for i in sys.argv:
xmpparse(root,i)
print(yaml.dump(d, default_flow_style=False))
当前输出:
disabled: 'false'
spec: H * * * *
任何帮助将不胜感激。提前致谢!
【问题讨论】:
-
对 YAML 了解不多(或任何...),但如果有帮助,我可以将您的字典转换为正确的格式(使用 lxml 库)。
-
我想要一个嵌套字典,仅用于我需要从 XML 中获取的条目。你能帮我解决这个问题吗?在进行递归操作时,它应该开始将值放入嵌套字典中
-
如果下面的答案有效,请告诉我。
标签: python-3.x dictionary xml-parsing