Python从指定URL解析XML并提取CRS标签信息的技术问询
解决Python提取XML中CRS标签的问题
嘿,我明白你已经成功拿到XML数据了,接下来的关键在于XML命名空间的处理——这是用ElementTree解析WMS GetCapabilities时最容易踩的坑!咱们一步步来搞定:
1. 先处理命名空间
你请求的这个WMS服务返回的XML使用了默认命名空间(http://www.opengis.net/wms),ElementTree不能直接用纯标签名CRS查找,必须带上命名空间才能定位到元素。
可以从根元素自动提取命名空间,或者直接手动定义:
# 获取根元素的命名空间 root = tree.getroot() namespace = root.tag.split('}')[0].strip('{') # 定义命名空间字典,方便后续调用 ns = {'wms': namespace}
2. 提取所有CRS标签内容
接下来用findall()结合命名空间,递归查找所有层级的<CRS>标签(因为CRS通常嵌套在Layer层级下,用//可以遍历所有子节点):
# 查找所有CRS标签 crs_elements = tree.findall('.//wms:CRS', namespaces=ns) # 提取每个CRS的文本内容并去重(可选,避免重复值) all_crs = list({crs.text.strip() for crs in crs_elements}) # 打印结果看看 print("所有CRS内容:") for crs in all_crs: print(crs)
3. 筛选特定CRS(比如只保留EPSG:4326)
如果后续要筛选特定CRS,直接在列表推导里加条件过滤就行:
# 筛选目标CRS,比如EPSG:4326 target_crs = 'EPSG:4326' filtered_crs = [crs for crs in all_crs if crs == target_crs] print(f"\n筛选出的{target_crs}:") for crs in filtered_crs: print(crs)
完整代码整合
把这些步骤加到你已有的代码里,完整版本如下:
import urllib.request, urllib.parse, urllib.error import xml.etree.ElementTree as ET url = 'https://wms.geonorge.no/skwms1/wms.adm_enheter_historisk?service=WMS&request=GetCapabilities' uh = urllib.request.urlopen(url) data = uh.read() tree = ET.fromstring(data) # 处理命名空间 root = tree.getroot() namespace = root.tag.split('}')[0].strip('{') ns = {'wms': namespace} # 提取所有CRS并去重 crs_elements = tree.findall('.//wms:CRS', namespaces=ns) all_crs = list({crs.text.strip() for crs in crs_elements}) print("所有CRS内容:") for crs in all_crs: print(crs) # 示例:筛选特定CRS target = 'EPSG:4326' filtered = [c for c in all_crs if c == target] print(f"\n筛选后的{target}:") print(filtered)
小提示
为什么必须处理命名空间?因为XML里的<CRS>实际上会被ElementTree解析成{http://www.opengis.net/wms}CRS,直接写findall('CRS')根本找不到对应的元素,这是新手最容易忽略的点哦~
内容的提问来源于stack exchange,提问作者Johs
相关产品推荐
相关产品推荐

