1

Here is my code and XML:

xml_string = """
<data>
    <user>
        <name>123</name>
    </user>
    <user>
        <name>456</name>
    </user>
</data>
"""

import xml.etree.ElementTree as ET
root = ET.fromstring(xml_string)

I'm trying to find <user> tag where <name> has text value equal to 123.

What I have tried:

result = root.findall("./user[name = '123']")
result = root.findall("./user[./name = '123']")
result = root.findall("./user[/name = '123']")
result = root.findall("./user[./name text() = '123']")

None of these attempts worked. What am I missing?

Error I'm getting:

raise SyntaxError("invalid predicate") 
File "<string>", line None
SyntaxError: invalid predicate
9
  • Maybe regex could work? Commented Jul 3, 2015 at 12:24
  • If this is what you're trying to find <name>123</name>, regex will do the job. Commented Jul 3, 2015 at 12:28
  • 7
    @JoeR that's exactly the opposite of the advice you should give; regex is not the best way to parse XML, which is not a regular language, see e.g. stackoverflow.com/questions/1732348/… Commented Jul 3, 2015 at 12:29
  • @jonrsharpe Yes, I agree and I would never suggest to parse HTML or XML using regex, however, if the OP just trying to find this one thing <name>123</name> that's an other story. Commented Jul 3, 2015 at 12:33
  • @JoeR but that isn't what the OP wants, they're after the user tag containing that. Commented Jul 3, 2015 at 12:39

1 Answer 1

8

As the exception says, it seems you have a syntax error in the predicate, there shouldn't be a space between the tag name and the value:

xml_string = """
<data>
    <user>
        <name>123</name>
    </user>
    <user>
        <name>456</name>
    </user>
</data>
"""

import xml.etree.ElementTree as ET
root = ET.fromstring(xml_string)

result = root.findall("./user[name='123']")

print result
Sign up to request clarification or add additional context in comments.

1 Comment

That's the thing! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.