使用Python插入XML值/元素 [英] Insert XML Value/Element with Python

查看:59
本文介绍了使用Python插入XML值/元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找向当前XML文件添加元素/值的解决方案.因此,假设我具有以下XML文件:

I've been looking all over for a solution to adding an element/value to a current XML file. So let's assume I have the following XML File:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Node>
        <Name>Sprinkler</Name>
        <Type>Blah</Type>
        <Prob>0.82</Prob>
    </Node>
    <Node>
        <Name>Rain</Name>
        <Type>Bleh</Type>
        <Prob>0.23</Prob>
    </Node>
    <Node>
        <Name>Cloudy</Name>
        <Type>Bluh</Type>
        <Prob>0.71</Prob>
    </Node>
</Root>

现在,我的目标是给定一个CSV文件,我想为每个节点添加新的元素和值.假设我的CSV包含以下内容:

Now, my goal is, given a CSV file, I want to add new elements and values per Node. Let's say that my CSV contains something like this:

Cloudy,Or,Sprinkler,Rain
Sprinkler,And,Rain
Rain,Or,Sprinkler,Cloudy

我能够毫无问题地读取CSV,我的问题是添加了新元素'Parent0'和'Parent1'(如果有),因此输出看起来像这样:

I was able to read the CSV without a problem, my problem is adding new elements, 'Parent0' and 'Parent1'(If any), so that the output looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Node>
        <Name>Sprinkler</Name>
        <Type>Blah</Type>
        <Prob>0.82</Prob>
        <Gate>And</Gate>
        <Parent0>Rain</Parent0>
    </Node>
    <Node>
        <Name>Rain</Name>
        <Type>Bleh</Type>
        <Prob>0.23</Prob>
        <Gate>Or</Gate>
        <Parent0>Sprinkler</Parent0>
        <Parent1>Cloudy</Parent1>
    </Node>
    <Node>
        <Name>Cloudy</Name>
        <Type>Bluh</Type>
        <Prob>0.71</Prob>
        <Gate>Or</Gate>
        <Parent0>Sprinkler</Parent0>
        <Parent1>Rain</Parent1>
    </Node>
</Root>

到目前为止,我已经用Python编写了以下内容:

So far I have written the following in Python:

import xml.etree.ElementTree as ET

xml = ET.parse('XML.xml')
for row in xml.iterfind('Node'):
    i = 1
    for item in csvFile:
        row.append('<Gate>'+item[1]+'</Gate>\n')
        if i != 1:
            for x in xrange(0, len(item):
                if row.findtext('Name') == item[x]:
                    row.append('<Parent0>'+item[x]+'</Parent0>\n')
        else:
            i = 0

在我的代码上,现在所有这些都将转到Parent0,但是我想看看如何在不删除所有内容的情况下进行追加?我听说过lxml和minidom,但是不确定它们是如何工作的.如果我能够使用xml.etree.ElementTree做到这一点,那就太好了.

On my code it will all go to Parent0 for now, but I wanted to see how it is possible to do the append, without deleting everything? I have a heard of lxml and minidom but not sure how these work. If I am able to do it using xml.etree.ElementTree, that would be fantastic.

推荐答案

一种简单的方法是使用

An easy way to do this would be to use ElementTree.SubElement() to create the elements, it would automatically add those elements to the end of the parent node, which is passed in as argument.

示例/演示-

>>> import xml.etree.ElementTree as ET
>>> import csv
>>> with open('test.csv','r') as f:
...     cfiles = list(csv.reader(f))
...
>>> xml = ET.parse('XML.xml')
>>> for row in xml.iterfind('.//Node'):
...     name = row.find('./Name').text
...     for i in cfiles:
...         if i[0] == name:
...             j = 1
...             while j < len(i):
...                 if j == 1:
...                     g = ET.SubElement(row,'Gate')
...                     g.text = i[j]
...                 elif j == 2:
...                     g = ET.SubElement(row,'Parent0')
...                     g.text = i[j]
...                 elif j == 3:
...                     g = ET.SubElement(row,'Parent1')
...                     g.text = i[j]
...                 j += 1
...
>>> print(ET.tostring(xml.getroot()).decode())
<Root>
    <Node>
        <Name>Sprinkler</Name>
        <Type>Blah</Type>
        <Prob>0.82</Prob>
    <Gate>And</Gate><Parent0>Rain</Parent0></Node>
    <Node>
        <Name>Rain</Name>
        <Type>Bleh</Type>
        <Prob>0.23</Prob>
    <Gate>Or</Gate><Parent0>Sprinkler</Parent0><Parent1>Cloudy</Parent1></Node>
    <Node>
        <Name>Cloudy</Name>
        <Type>Bluh</Type>
        <Prob>0.71</Prob>
    <Gate>Or</Gate><Parent0>Sprinkler</Parent0><Parent1>Rain</Parent1></Node>
</Root>

在上面, cfiles 是我先前从csv文件创建的列表.

Here above , cfiles is a list I have previously created from the csv file.

要将xml写入新文档,请执行-

For writing the xml to a new document, do -

with open('newxml.xml','w') as of:
    of.write(ET.tostring(xml.getroot()).decode())

这篇关于使用Python插入XML值/元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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