附加到XML标记内的文本

时间:2016-11-29 23:48:49

标签: python xml lxml elementtree

我正试图找出一种方法,使用ElementTree 附加到XML标记中的字符串。

基本上我想制作:

<gco:CharacterString>

2016-08-11 13:52:15  -  Bob Smith
fourth comment yadayada

2016-08-11 13:53:34  -  Bob Smith
third comment blah

2016-10-17 11:13:41  -  Bob Smith
second comment

2016-10-25 10:53:19  -  Bob Smith
first comment

</gco:CharacterString>

每次用户进入评论时,都会附加评论和日期标记。

我通常会建立一个这样的标签:

historystrings = ET.SubElement(statement,"
{http://www.isotc211.org/2005/gco}CharacterString").text = (datestamp,comment)  # SOURCE HERE

但不确定如何使用元素树追加,以便保留以前条目的记录。

2 个答案:

答案 0 :(得分:3)

首先,您需要以某种方式访问​​现有元素。例如,像这样:

gco_cs = root.find('{http://www.isotc211.org/2005/gco}CharacterString')

然后您可以修改.text属性,如下所示:

gco_cs.text += '\nSome new data\n'

这是一个完整的例子:

foo.py

import xml.etree.ElementTree as ET
tree = ET.parse('foo.xml')
root = tree.getroot()

gco_cs = root.find('{http://www.isotc211.org/2005/gco}CharacterString')
gco_cs.text += '\nSome new data\n'

ET.dump(root)

foo.xml

<foo xmlns:gco="http://www.isotc211.org/2005/gco">
<gco:CharacterString>
some text
</gco:CharacterString>
</foo> 

结果:

$ python foo.py 
<foo xmlns:ns0="http://www.isotc211.org/2005/gco">
<ns0:CharacterString>
some text

Some new data
</ns0:CharacterString>
</foo>

答案 1 :(得分:0)

看看我为自己写的这部分剧本:

class Module():

def moduleLine(self):

    with open("/root/custom-nginx/nginx/debian/rules","r") as rules:

        lines = rules.readlines()

        for line in lines:

            if line.startswith("full_configure_flags"):
                full_index = str(line)

        findex = lines.index(full_index)

    for line in lines[int(findex)+1:]:

        if line.endswith(":= \\\n"):
            second_index = str(line)
            break
        else:
            continue

    sindex = lines.index(second_index)
    add_line = sindex-3

    rules.close()
    return add_line

def addModule(self,index):

    with open("/root/custom-nginx/nginx/debian/rules", "r") as file:
        data = file.readlines()
        data[index] = data[index] + "\t"*3 + "--add-module=$(MODULESDIR)/ngx_pagespeed \\" + "\n"
    file.close()
    with open("/root/custom-nginx/nginx/debian/rules","w") as file:
        file.writelines(data)
    file.close()

在&#39; moduleLine&#39;函数它打开一个名为rules的文件,并按readlines()(行变量)

读取行

之后if语句出现并检查该行是否与我想要的字符串匹配,并且findex包含行号。

如果您有一个特定的xml文件,并且您知道行号,则可以直接在您的python代码中使用行号。

查看addModule函数,它附加字符串--add-module = $(MODULESDIR)/ ngx_pagespeed \&#34; +&#34; \ n&#34;在data[index]哪个索引是行号。

您可以使用此基础将字符串附加到xml文件中。