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

2024-05-19 19:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经把XML输入为国家.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>

Tags: keynamecitysourcenewvalrootxml
1条回答
网友
1楼 · 发布于 2024-05-19 19:28:57

Comment: What if diction:{'AUSTRALIA': ['MELBOURNE']} ? And I want to keep both the things from dictionary as well as from input xml into output xml?

  • .clear附近添加一个条件

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

Question: How to update existing xml element with new given <val>...</val>?

文档: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'):
    
  • 获取此nameelement

        name = element.find('name')
    
  • 获取这个table_categoryelement.clear

        table_category = element.find('table_category')
        table_category.clear()
    
  • 循环为[name.text]定义的dictionlist的所有项。你知道吗

        for val in diction[name.text]:
    
  • table_category后面加一个新的<val>val</val>

            table_category.append(VAL(val))
    

Output: print('{}'.format(etree.tostring(root, pretty_print=True).decode()))

<configroot version="8.0">
<set>
    <name>Countries</name>
    <elements>
    <name>US</name>
    <table_category><val>New York</val><val>Chicago</val></table_category></elements>
    <elements>
    <name>UK</name>
    <table_category><val>OXFORD</val><val>London</val></table_category></elements>
</set>
</configroot>

用Python:3.5测试

相关问题 更多 >