我有一个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
谢谢
您必须查询整个节点,而不仅仅是查询其内容:
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)
就这样!:)