Re: Finding all instances of a string in an XML file

Discussion in 'Python' started by Jason Friedman, Jun 23, 2013.

  1. > 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.
    Jason Friedman, Jun 23, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Wohlbier
    Replies:
    2
    Views:
    366
    Josiah Carlson
    Feb 22, 2004
  2. Jason Friedman
    Replies:
    0
    Views:
    134
    Jason Friedman
    Jun 21, 2013
  3. Peter Otten
    Replies:
    0
    Views:
    130
    Peter Otten
    Jun 21, 2013
  4. dieter
    Replies:
    0
    Views:
    115
    dieter
    Jun 21, 2013
  5. Jason Friedman
    Replies:
    0
    Views:
    118
    Jason Friedman
    Jun 21, 2013
Loading...

Share This Page