在命名空间中的属性上设置新值

时间:2017-03-29 09:34:26

标签: python xpath lxml

我有这个xml(它是更扩展的一部分)我正在使用python和lxml进行解析

<om:OM_Observation gml:id="observation">
 <gml:description>Wind Speed</gml:description>     
 <om:phenomenonTime xlink:href="#phenomenonTime"/>
 <om:resultTime xlink:href="#phenomenonTime"/>
 <om:procedure xlink:href="procedure"/>
 <om:observedProperty xlink:href="WS_5min_avg"/>
 <om:featureOfInterest xlink:href="#FOI"/>
 <om:result xsi:type="gml:MeasureType" uom="m/s">568</om:result>
</om:OM_Observation>

我能够在标签中获取文本值并更改其值并更新文件data.xml:

from lxml import etree
data='data.xml'
data_tree = etree.parse(data)
root = data_tree.getroot()
nsmap = {'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xlink': 'http://www.w3.org/1999/xlink',  'gml': 'http://www.opengis.net/gml/3.2',  'om': 'http://www.opengis.net/om/2.0'}

result=data_tree.xpath("//om:OM_Observation/om:result", namespaces=nsmap)
result[0].text="114"    
etree.ElementTree(root).write(data, xml_declaration=True, encoding='utf-8', method="xml", pretty_print=True)

我想要做的是更改属性的值并更新xml文件。 我正在尝试类似的方法,但它不起作用。我能够获得属性的值:

 featureOfInterest_attr=tree.xpath("//om:featureOfInterest/@xlink:href", namespaces=nsmap)

但如果我想使用以下方法更改其值:

tree.xpath("//om:featureOfInterest/@xlink:href",namespaces=nsmap)="#newFOI"
etree.ElementTree(root).write(data, xml_declaration=True,encoding='utf-8', method='xml', pretty_print=True)

未插入新值。 我做错了什么?

1 个答案:

答案 0 :(得分:2)

您的上一个代码段与成功的代码存在重大差异。 xpath()返回列表,因此您必须使用索引指定列表中的哪个项目需要更新:

result = tree.xpath("//om:featureOfInterest/@xlink:href",namespaces=nsmap)
result[0] = "#newFOI"
# or
# tree.xpath("//om:featureOfInterest/@xlink:href",namespaces=nsmap)[0] = "#newFOI"

显然,我们无法更新使用xpath()直接选择的属性,因为返回值只是字符串列表。因此,在这种情况下,result[0] = ...仅更新列表中第一项的值,并且根本不会影响源XML树。我们需要获取属性的父级,然后从那里更新:

result = tree.xpath("//om:featureOfInterest",namespaces=nsmap)
result[0].attrib['{%s}href' % nsmap['xlink']] = "#newFOI"
相关问题