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

标签 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>

最佳答案

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/

相关文章:

python - 调用父类(super class)的 __call__ 方法

python - While 循环未检测到 msvcrt.getch() 按键

python - 让函数相互交互的正确方法

xml - 比较 JUnit 中的 XML 元素

python - Django:类型错误:上下文必须是 dict 而不是 str

python - 在新的 subprocess.Popen 对象列表上使用 poll()

javascript - XML/javascript 解析节点 - 按名称指定子节点

performance - 将 XML 文档转换为二进制文件是什么意思?

python - 类之间共享属性 : is multi-inheritance right and "pythonic" here?

python - 为什么 OLS 回归模型中除了第一个(截距)之外的所有系数都获得非常接近零(e^-17 或低)的值?