gpt4 book ai didi

python - 为命名空间中的属性设置新值

转载 作者:行者123 更新时间:2023-12-01 03:08:56 24 4
gpt4 key购买 nike

我有这个 xml(它是更扩展的 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)

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

最佳答案

您的最后一个代码片段与您的成功代码有着至关重要的区别。 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"

关于python - 为命名空间中的属性设置新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43089699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com