我正在嘗試使用 Python ElementTree 更新 xml 中的屬性值,當我嘗試訪問該屬性時,我收到一條訊息
沒有任何
這是xml資料
xmldata='''<?xml version="1.0" encoding="UTF-8"?>
<WMS_Capabilities version="1.3.0" xmlns="http://www.opengis.net/wms" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wms http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd">
<!-- Service Metadata -->
<Capability>
<Request>
<GetCapabilities>
<Format>text/xml</Format>
<DCPType>
<HTTP>
<Get>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
xlink:type="simple"
xlink:href="http://localhost:8080" />
</Get>
<Post>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
xlink:type="simple"
xlink:href="http://localhost:8080" />
</Post>
</HTTP>
</DCPType>
</GetCapabilities>
<GetMap>
<Format>image/jpg</Format>
<Format>image/png</Format>
<DCPType>
<HTTP>
<Get>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink"
xlink:type="simple"
xlink:href="http://localhost:8080" />
</Get>
</HTTP>
</DCPType>
</GetMap>
<GetFeatureInfo>
<Format>text/xml</Format>
<Format>text/plain</Format>
<Format>text/html</Format>
</GetFeatureInfo>
</Request>
<Exception>
<Format>XML</Format>
<Format>INIMAGE</Format>
<Format>BLANK</Format>
</Exception>
</Capability>
</WMS_Capabilities>'''
ns='{http://www.opengis.net/wms}'
myroot = ET.fromstring(xmldata)
for x in myroot.findall(ns "Capability/" ns "Request/" ns "GetMap/" ns "DCPType/" ns "HTTP/" ns "Get/" ns "OnlineResource"):
print(x)
輸出:
<元素'{http://www.opengis.net/wms}OnlineResource' at 0x7f0e0ab8e130>
selectedNode=myroot.find(ns "Capability/" ns "Request/" ns "GetMap/" ns "DCPType/" ns "HTTP/" ns "Get/" ns "OnlineResource").tag
print(selectedNode)
輸出:
{http://www.opengis.net/wms}在線資源
selectedAttribute=myroot.find(ns "Capability/" ns "Request/" ns "GetMap/" ns "DCPType/" ns "HTTP/" ns "Get/" ns "OnlineResource").attrib['xlink:href']
print(selectedAttribute)
輸出:
Traceback (most recent call last): File "<string>", line 59, in
<module> KeyError: 'xlink:href'
在這里,我想更新屬性“xlink:href”的值并保存 xml 檔案。
我無法訪問該屬性,并在嘗試訪問它時出錯。我不知道我是否遵循了正確的方法來訪問屬性值。需要建議來更新值。
我參考了下面提到的鏈接,
- 如何使用 Python ElementTree 提取 xml 屬性
- 如何使用 xpath 在 XML(包括深度嵌套的元素)中獲取 *any* 元素的 href 屬性?
- 如何在 Python 中提取 XML 屬性的值?
- 在 Python 中讀取 XML 檔案并獲取其屬性值
- https://docs.python.org/3/library/xml.etree.elementtree.html
- https://www.edureka.co/blog/python-xml-parser-tutorial/
uj5u.com熱心網友回復:
似乎為了訪問href
屬性,欄位名稱必須以xlink
屬性的值作為前綴。繼續您的示例代碼:
>>> node = myroot.find(ns "Capability/" ns "Request/" ns "GetMap/" ns "DCPType/" ns "HTTP/" ns "Get/" ns "OnlineResource")
>>> node.attrib['{http://www.w3.org/1999/xlink}href']
'http://localhost:8080'
如果您事先不知道此前綴,您應該仍然可以href
使用此方法在運行時找到該欄位:
for key, val in node.attrib.items():
if key.endswith('href'):
print(val)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/508600.html