使用lxml更改文本值

时间:2013-11-14 16:17:40

标签: python lxml

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

  <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}。

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

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

由于

1 个答案:

答案 0 :(得分:17)

您必须查询整个节点而不是仅查询其内容:

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

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

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)

这就是全部! :)