我正在尝试在Python中解析一个XML字符串。例如:
<policy-maps>
<policy-map>
<type>qos</type>
<name>PROFILE1</name>
<policy-map-rule>
<class-name>voice</class-name>
<class-type>qos</class-type>
<priority-level>1</priority-level>
<police>
<rate>
<value>30</value>
<units>percent</units>
</rate>
</police>
<queue-limit>
<value>17</value>
<unit>kbytes</unit>
</queue-limit>
</policy-map-rule>
<policy-map-rule>
<class-name>video</class-name>
<class-type>qos</class-type>
<police>
<rate>
<value>10</value>
<units>percent</units>
</rate>
<burst>
<value>5000</value>
<units>bytes</units>
</burst>
</police>
</policy-map-rule>
</policy-map>
</policy-maps>我想要提取标签"policy-map“中的所有内容,或者在某个"policy-map”和"class-name“中的标签”policy“中提取所有内容。我已经尝试了我能找到的每一个例子,但似乎没有一个例子是我想要做的或工作的。有什么帮助吗?谢谢。
发布于 2018-03-07 06:16:29
有很多方法可以剥这只猫的皮。但由于您的数据不使用属性,因此转换为字典对您来说可能是最容易的。(您可能还喜欢untangle包。)
注在下面的示例中,我已经使用xmltodict将xml转换为嵌套的有序字典,然后您可以使用标准字典方法来处理结果。
import xmltodict
import pprint
xml = """
.... YOUR XML GOES HERE
"""
doc = xmltodict.parse(xml)
pp = pprint.PrettyPrinter(depth=6)
pp.pprint(doc['policy-maps']['policy-map']['policy-map-rule'])收益率;
[OrderedDict([('class-name', 'voice'),
('class-type', 'qos'),
('priority-level', '1'),
('police',
OrderedDict([(...)])),
('queue-limit',
OrderedDict([('value', '17'), ('unit', 'kbytes')]))]),
OrderedDict([('class-name', 'video'),
('class-type', 'qos'),
('police',
OrderedDict([(...), (...)]))])]https://stackoverflow.com/questions/49140681
复制相似问题