You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python ElementTree解析XML并提取Vertices节点值

使用Python ElementTree提取XML中节点内容

步骤说明

Python的xml.etree.ElementTree是原生XML解析库,无需额外安装,可通过以下步骤提取目标节点:

  1. 导入ElementTree模块
  2. 加载XML(从文件或字符串,注意XML必须格式完整,你提供的片段缺少闭合标签,需补全后再处理)
  3. 通过XPath路径精准定位<Vertices>节点
  4. 根据需求提取子节点属性或节点的原始XML内容

代码示例

情况1:从文件读取XML

假设你的XML文件已补全闭合标签(如</Parameter></Parameter></Parameter></Method>),保存为method.xml:

import xml.etree.ElementTree as ET

# 加载XML文件
tree = ET.parse('method.xml')
root = tree.getroot()

# 通过XPath定位Vertices节点
vertices_node = root.find(".//Parameter[@key='PolygonRegion']/Value/Vertices")

# 提取所有<V>节点的坐标属性
print("所有顶点坐标:")
for v in vertices_node.findall('V'):
    x_coord = v.get('x')
    y_coord = v.get('y')
    print(f"x: {x_coord}, y: {y_coord}")

# 提取Vertices节点的完整XML字符串(可选)
vertices_xml = ET.tostring(vertices_node, encoding='utf-8').decode('utf-8')
print("\nVertices节点完整内容:")
print(vertices_xml)

情况2:直接解析XML字符串

先补全你提供的XML片段的闭合标签,再解析:

import xml.etree.ElementTree as ET

# 补全后的XML字符串
xml_content = '''<?xml version="1.0" encoding="utf-8"?>
<Method>
  <Version>1.0</Version>
  <Parameter key="IM-MS Browser Method">
   <Parameter key="FileOperations">
      <Parameter key="CondenseFilePSet">
        <Parameter key="AutoFrameSelect">
          <Value>True</Value>
        </Parameter>
    </Parameter>
    <Parameter key="MethodBookmark">
      <Parameter key="MassRange">
        <Value />
      </Parameter>
      <Parameter key="PolygonRegion">
        <Value>
          <XUnits>Milliseconds</XUnits>
          <YUnits>MassToCharge</YUnits>
          <Vertices>
            <V x="0.2705684" y="102.2292" />
            <V x="59.79562" y="3173.849" />
            <V x="0.676421" y="3173.849" />
            <V x="0.2705684" y="142.8233" />
          </Vertices>
        </Value>
      </Parameter>
    </Parameter>
  </Parameter>
</Method>'''

# 解析字符串
root = ET.fromstring(xml_content)

# 定位并提取内容
vertices_node = root.find(".//Parameter[@key='PolygonRegion']/Value/Vertices")

print("所有顶点坐标:")
for v in vertices_node.findall('V'):
    print(f"x: {v.get('x')}, y: {v.get('y')}")

关键说明

  • XPath路径.//Parameter[@key='PolygonRegion']/Value/Vertices中,.//表示递归查找所有子节点,[@key='xxx']用于匹配带指定属性的节点
  • 若XML结构有变化,需调整XPath路径以匹配实际节点层级
  • 必须确保XML格式完整,否则解析时会抛出语法错误

内容的提问来源于stack exchange,提问作者Snow32

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 14:06:18