简体   繁体   English

在 XML 中获取(和求和)所有名为“test”的属性的值

[英]Get (and sum) values of all attributes named 'test' in XML

Example XML doc: XML 文档示例:

<main>
  <this test="500">
    <that test="200"/>
  </this>
</main>

Result: 700结果:700

All the existing code snippets I've found on this site and others rely on a tag.我在本网站和其他网站上找到的所有现有代码片段都依赖于一个标签。 For example, you could only get "500" if you reference both "this" and "test".例如,如果同时引用“this”和“test”,则只能得到“500”。 I'm looking to search only for "test" throughout the entire doc/string.我只想在整个文档/字符串中搜索“测试”。

Some modules that I've tried (and resulted in failure) are lxml, xml.dom, ElementTree, xmltodict, and BeautifulSoup,我尝试过(并导致失败)的一些模块是 lxml、xml.dom、ElementTree、xmltodict 和 BeautifulSoup,

I'd suggest to favor lxml for parsing XML in python.我建议使用lxml在 python 中解析 XML。 lxml has full xpath 1.0 support, and xpath is the language/technology designed specifically for querying XML. lxml具有完整的xpath 1.0支持,xpath 是专为查询 XML 设计的语言/技术。

Once you have the right tool for the right job, you can do something like this fe :一旦你有合适的工具来做合适的工作,你可以做这样的事情 fe :

import lxml.etree as et

xml = """<main>
  <this test="500">
    <that test="200"/>
  </this>
</main>"""
doc = et.fromstring(xml)
result = doc.xpath("sum(//@test)")
print(result)

output :输出 :

700.0

brief explanation about xpath being used :关于正在使用的 xpath 的简要说明:

  • //@test : find all test attribute anywhere in the XML document. //@test : 查找 XML 文档中任意位置的所有test属性。
  • sum() : return sum of the parameter sum() : 返回参数的总和

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM