在XML标签内添加文本

2024-06-10 10:28:58 发布

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

我正在设法使用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>

每次用户输入评论时,它都会附加评论并给它加上日期戳。在

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

^{pr2}$

但不知道如何使用元素树进行追加,这样它就可以记录以前的条目。


Tags: 字符串标记comment评论xmlbobsmithblah
2条回答

看看我为自己写的剧本:

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()

在'moduleLine'函数中,它打开一个名为rules的文件,并通过readlines()(lines变量)读取该行

之后,if语句来检查行是否与我想要的字符串匹配,findex包含行号。在

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

看一下addModule函数,它将add module=$(MODULESDIR)/ngx\u pagespeed\“+”\n“字符串附加在data[index]的索引处,该字符串是行号。在

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

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

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

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

^{pr2}$

下面是一个完整的例子:

在食品

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>

相关问题 更多 >