使用lxml更改文本值 [英] Change text value with lxml

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

问题描述

我有一个xml文件-这是一个代码段.

I have an xml file - here is a snippet..

  <gmd_fileIdentifier>
    <gco_CharacterString>{0328cb65-b564-495a-b17e-e49e04864ab7}</gco_CharacterString>
 </gmd_fileIdentifier>
          <gmd_identifier>
            <gmd_RS_Identifier>
              <gmd_authority gco_nilReason="missing" />
              <gmd_code>
                <gco_CharacterString>0000</gco_CharacterString>
              </gmd_code>
              <gmd_codeSpace xmlns:gml="http://www.opengis.net/gml" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
                  <gco_CharacterString>test</gco_CharacterString>
                </gmd_codeSpace>
            </gmd_RS_Identifier>
          </gmd_identifier>

我要做的是将标记中当前的0000值更改为gmd_fileIdentifier字符串{0328cb65-b564-495a-b17e-e49e04864ab7}.

What I want to do is change the value of 0000 which is currently in the tag, to the gmd_fileIdentifier character string {0328cb65-b564-495a-b17e-e49e04864ab7}.

我可以使用以下python代码访问值,但是如何设置值? 当前代码

I can access the values, using the following python code, but how do I set the value? Current code

import os, sys
from lxml import etree

myXML = r"D:\test.xml"
tree = etree.parse(myXML)
root = tree.getroot()
root.xpath("//gmd_fileIdentifier/gco_CharacterString/text()")
print fileID
code = root.xpath("//gmd_identifier/gmd_RS_Identifier/gmd_code/gco_CharacterString/text()")
print code

谢谢

推荐答案

您将不得不查询整个节点,而不仅仅是查询其内容:

You'll have to query the whole node instead of only its contents:

code = root.xpath('//gmd_identifier/gmd_RS_Identifier/gmd_code/gco_CharacterString')

然后,如果匹配,只需替换其文本并保存回XML文件:

Then, if it matched, just replace its text and save back to the XML file:

if code:
    # Replaces <gco_CharacterString> text
    code[0].text = '{0328cb65-b564-495a-b17e-e49e04864ab7}'
    # Save back to the XML file
    etree.ElementTree(root).write('D:\test.xml', pretty_print=True)

仅此而已! :)

这篇关于使用lxml更改文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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