python - Get (and sum) values of all attributes named 'test' in XML -
example xml doc:
<main> <this test="500"> <that test="200"/> </this> </main>
result: 700
all existing code snippets i've found on site , others rely on tag. example, "500" if reference both "this" , "test". i'm looking search "test" throughout entire doc/string.
some modules i've tried (and resulted in failure) lxml, xml.dom, elementtree, xmltodict, , beautifulsoup,
i'd suggest favor lxml
parsing xml in python. lxml
has full xpath 1.0 support, , xpath language/technology designed querying xml.
once have right tool right job, can f.e :
import lxml.etree 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 xpath being used :
//@test
: findtest
attribute anywhere in xml document.sum()
: return sum of parameter
Comments
Post a Comment