基于python和ElementT的XML属性解析

2024-09-30 14:20:42 发布

您现在位置:Python中文网/ 问答频道 /正文

伙计们! 我试图解析一些奇怪的XML格式:

<?xml version="1.0" encoding="UTF-8"?>
<analytics>
  <standard1>
    ...
    <attributes>
      <attribute name="agentname" value="userx userx" />
      <attribute name="agentpk" value="5" />
      <attribute name="analytics:callid" value="757004000003597" />
      ...
      <attribute name="wrapuptime" value="0" />
    </attributes>
  </standard1>
  <standard2>
    ...
    <attributes>
      <attribute name="agentname" value="userx userx" />
      <attribute name="agentpk" value="5" />
      <attribute name="analytics:callid" value="757004000003597" />
      ...
      <attribute name="wrapuptime" value="0" />
    </attributes>
  </standard2>
  <engines>
  ...
  </engines>
</analytics>

因为namevalue都是属性,我不知道如何通过name访问value,而不必循环整个属性子段。在

你知道如何使用ElementTree直接访问吗?在


Tags: namevalueattributexmlattributesanalyticsengines伙计
1条回答
网友
1楼 · 发布于 2024-09-30 14:20:42

您可以使用一个简单的XPath表达式按name属性的值过滤attribute元素。样本工作代码:

import xml.etree.ElementTree as ET

data = """<?xml version="1.0" encoding="UTF-8"?>
<analytics>
  <standard>
      <attributes>
        <attribute name="agentname" value="userx userx" />
        <attribute name="agentpk" value="5" />
        <attribute name="analytics:callid" value="757004000003597" />
        <attribute name="wrapuptime" value="0" />
      </attributes>
  </standard>
</analytics>
"""

root = ET.fromstring(data)
print(root.find(".//attribute[@name='agentname']").attrib["value"])

印刷品:

^{pr2}$

注意xml.etree.ElementTree有一个limited XPath support。在

相关问题 更多 >