如何使用python使用新的给定元素更新现有xml元素?

时间:2019-01-09 13:39:30

标签: python xml python-3.x

我已输入XML作为country.xml:-

<root>
<set>
    <name>Countries</name>
    <elements>
    <name>US</name>
    <city>
        <val>New York</val>
        <val>Las Vegas</val>
    </city>
    </elements>
    <elements>
    <name>UK</name>
    <city>
        <val>London</val>
    </city>
    </elements>
</set>
</root>

我正在解析xml并将其放入列表中,并且我有一个字典,基于该字典我可以比较和添加xml元素。

diction: dict = {'US':['New York', 'Chicago'], 'UK':['OXFORD', 'London']}
source = etree.getroot()
for key,value in diction.items()
    countrylist = source.xpath('./elements/name[text()=\'{}\']/..'.format(key))
    if len(countrylist) == 0:
        # creating new string and element
        # appending element to original tree
    elif len(countrylist) == 1:   ###This is problematic case what to expect here to update key,value from dictionary only and replace the tag already present in xml
        key = countrylist[0]
    else:
        countinue

    # writebacktoxml(source,"country.xml")

我得到的输出是原始输入条件,因为它在特定条件下处于输出状态。 预期输出如下:-

<root>
<set>
    <name>Countries</name>
    <elements>
    <name>US</name>
    <city>
        <val>New York</val>
        <val>Chicago</val>
    </city>
    </elements>
    <elements>
    <name>UK</name>
    <city>
        <val>OXFORD</val>
        <val>London</val>
    </city>
    </elements>
</set>
</root>

1 个答案:

答案 0 :(得分:1)

  

评论:如果diction:{'AUSTRALIA': ['MELBOURNE']}怎么办?而且我想同时保留字典中的内容以及输入xml到输出xml中的内容?

  • .clear周围添加条件

    if name.text in ['AUSTRALIA']:
        # Keep the values
        pass
    else:
        table_category.clear()
    

  

问题:如何使用给定的<val>...</val>更新现有的xml元素?

文档:The lxml.etree Tutorial - The E-factory
Python Documentation -The ElementTree XML API - Modifying an XML File


  • 使用lxml

    的示例
    from lxml import etree
    from lxml.builder import ElementMaker
    
  • 数据dict

    diction = {'US': ['New York', 'Chicago'], 'UK': ['OXFORD', 'London']}
    
  • 实例化一个ElementMaker对象和一个新的<val>...</val>对象。

    E = ElementMaker()
    VAL = E.val
    
  • 解析源xml

    tree = etree.parse(io.StringIO(xmlf))
    root = tree.getroot()
    
  • 解析所有set/elements

    for element in root.findall('set/elements'):
    
  • 获取此name的{​​{1}}

    element
  • 获取此 name = element.find('name') 的{​​{1}}并table_category

    element
  • .clear定义的 table_category = element.find('table_category') table_category.clear() list所有个项目。

    diction
  • [name.text]上添加 for val in diction[name.text]:

    <val>val</val>
  

输出table_category

        table_category.append(VAL(val))

使用Python测试:3.5