XML<&ARG GT;在Python值置换 [英] XML <arg> value Replacement in Python

查看:331
本文介绍了XML<&ARG GT;在Python值置换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关以下sample.xml的文件,我怎么更换ARG键类型A和B型分别使用Python的价值?

sample.xml中:

 <样品>
            <适配器类型=ABCDEF>
                <精氨酸键=A型VALUE =真/>
                <精氨酸键=B型VALUE =真/>
            < /适配器>
        < /样品>

这是我如何处理在Python的arg属性:

  =树ET.parse('sample.xml中')
在tree.iterfind节点('.//记录/适配器[@类型=ABCDEF]'):
    对于孩子节点:
        child.set('值','假')#此更改这两个值假


解决方案

您可以通过勾选关键==A型/B类获取方式,就像这样:

 在tree.iterfind节点('.//记录/适配器[@类型=ABCDEF]'):
    对于孩子节点:
        #检查关键是A型
        如果child.get('键')=='A型':
            child.set('值','假')
        #...如果B类......

其实,你可以通过使用更好的XPath直接访问改善你的code:

 在tree.iterfind节点('.//记录/适配器[@类型=ABCDEF] / ARG):
    #所以你不需要另一个内环访问<&ARG GT;分子
    如果node.get('键')=='A型':
        node.set('值','假')
    #...如果B类......

For the following sample.xml file, how do I replace the value of arg key "Type A" and "Type B" separately using Python?

sample.xml:

        <sample>
            <Adapter type="abcdef">
                <arg key="Type A" value="true" />
                <arg key="Type B" value="true" />
            </Adapter>
        </sample>

This is how I approach to the arg attribute in Python:

tree = ET.parse('sample.xml')
for node in tree.iterfind('.//logging/Adapter[@type="abcdef"]'):
    for child in node:
        child.set('value', 'false') #This change both values to "false"

解决方案

You can check the "key" == 'Type A' / 'Type B' by using get method, like this:

for node in tree.iterfind('.//logging/Adapter[@type="abcdef"]'):
    for child in node:
        # check if the key is 'Type A'
        if child.get('key') == 'Type A':
            child.set('value', 'false')
        # ... if 'Type B' ...

In fact, you can improve your code by using a better xpath accessing directly:

for node in tree.iterfind('.//logging/Adapter[@type="abcdef"]/arg'):
    # so you don't need another inner loop to access <arg> elements
    if node.get('key') == 'Type A':
        node.set('value', 'false')
    # ... if 'Type B' ...

这篇关于XML&LT;&ARG GT;在Python值置换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆