首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用lxml替换XML上的文本?

如何用lxml替换XML上的文本?
EN

Stack Overflow用户
提问于 2017-06-09 02:14:53
回答 1查看 2.3K关注 0票数 2

我正在尝试在一个xml文件上运行几个element.text。我成功地获得了两个列表,第一个列表将前面的element.text重新组合为str (long_name)太长,第二个列表在troncation (short_name)之后重新分组。

现在我想替换xml上的element.text,我尝试了一些脚本,但为了使用函数readline(),我想找到类似的lxml解决方案,如下代码所示:

代码语言:javascript
复制
txt = open('IF_Generic.arxml','r')
Lines = txt.readlines()
txt.close()

txt = open('IF_Genericnew.arxml','w')

for e in range(len(long_name)) :
    for i in range(len(Lines)) :
        if (long_name[e] in Lines[i]) == True :
            Lines[i] = Lines[i].replace(long_name[e],short_name[e])

for i in Lines :
     txt.write(i)

txt.close()

我试过了,但没用:

代码语言:javascript
复制
f = open('IF_Generic.arxml')
arxml = f.read()
f.close()
tree = etree.parse(StringIO(arxml))
for e,b in enumerate(long_name) :
    context = etree.iterparse(StringIO(arxml))
    for a,i in context:
        if not i.text:
            pass
        else:
            if (b in i.text) == True :
                i.text = short_name[e]

obj_arxml = etree.tostring(tree,pretty_print=True)

f = open('IF_Genericnew.arxml','w')
f.write(obj_arxml)
f.close()

假设列表long_name的第一个元素是RoutineServices_EngMGslLim_NVMID03

代码语言:javascript
复制
<BALISE_A>
    <BALISE_B>
        <SHORT-NAME>RoutineServices_EngMGslLim_NVMID03</SHORT-NAME>
    </BALISE_B>
</BALISE_A>
<BALISE_C>
    <POSSIBLE-ERROR-REF DEST="APPLICATION-ERROR">/Interfaces/RoutineServices_EngMGslLim_NVMID03/E_NOT_OK</POSSIBLE-ERROR-REF>
    <SHORT-NAME>Blah_Bleh_Bluh</SHORT-NAME>
</BALISE_C>

列表short_name的第一个元素是RoutineServices_EngMGslLim_NV

代码语言:javascript
复制
<BALISE_A>
    <BALISE_B>
        <SHORT-NAME>RoutineServices_EngMGslLim_NV</SHORT-NAME>
    </BALISE_B>
</BALISE_A>
<BALISE_C>
    <POSSIBLE-ERROR-REF DEST="APPLICATION-ERROR">/Interfaces/RoutineServices_EngMGslLim_NV/E_NOT_OK</POSSIBLE-ERROR-REF>
    <SHORT-NAME>Blah_Bleh_Bluh</SHORT-NAME>
</BALISE_C>

我想要这个

P.S:我使用python 2.7.9

提前谢谢大家!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-09 09:40:56

不要像打开文本文件那样打开XML文件。--我有explained in this answer --为什么这是个坏主意。

只需让etree读取和写入文件即可。它也减少了编写的代码。

代码语言:javascript
复制
from lxml import etree

# read the file and load it into a DOM tree
tree = etree.parse('IF_Generic.arxml')


for elem in tree.iterfind("//*"):
    # find elements that contain only text
    if len(elem) == 0 and elem.text and elem.text.strip() > '':
        # do your replacements ...
        elem.text = "new text"


# serialize the DOM tree and write it to file
tree.write('IF_Genericnew.arxml', pretty_print=True)

您可以使用更具体的"//*"来缩小您想要处理的元素,而不是遍历所有的元素(这就是"//*"所做的)。

例如,像"//SHORT-NAME | //POSSIBLE-ERROR-REF"这样的东西将有助于减少整个工作负载。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44448251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档