gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:27:47 31 4
gpt4 key购买 nike

我已输入 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>

最佳答案

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'):
  • 获取name这个element

        name = element.find('name')
  • 获取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))

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

关于python - 如何使用 python 使用新的给定元素更新现有的 xml 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54111475/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com