Finding all instances of a string in an XML file

Jason Friedman jsf80238 at gmail.com
Sun Jun 23 15:15:01 EDT 2013


> xml = """<?xml version="1.0" encoding="UTF-8"?>
> <!DOCTYPE KMART SYSTEM "my.dtd">
> <LEVEL_1>
>   <LEVEL_2 ATTR="hello">
>     <ATTRIBUTE NAME="Property X" VALUE ="2"/>
>   </LEVEL_2>
>   <LEVEL_2 ATTR="goodbye">
>     <ATTRIBUTE NAME="Property Y" VALUE ="NULL"/>
>     <LEVEL_3 ATTR="aloha">
>       <ATTRIBUTE NAME="Property X" VALUE ="3"/>
>     </LEVEL_3>
>     <ATTRIBUTE NAME="Property Z" VALUE ="welcome"/>
>   </LEVEL_2>
> </LEVEL_1>
> """
>
> import xml.etree.ElementTree as etree
>
> tree = etree.fromstring(xml)
>
> def walk(elem, path, token):
>     path += (elem,)
>     if token in elem.attrib.values():
>         yield path
>     for child in elem.getchildren():
>         for match in walk(child, path, token):
>             yield match
>
> for path in walk(tree, (), "Property X"):
>     print(", ".join("{} {}".format(elem.tag, elem.attrib) for elem in
> path))
>
> Peter, thank you, that exactly meets my need.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130623/71fc60ad/attachment.html>


More information about the Python-list mailing list