0

I have XML along the following lines:

<?xml version="xxx"?>
<doc:document xmlns:doc="some value 1...">
    <rdf:RDF xmlns:rdf="some value 2...">
        <rdf:Description rdf:about="some value...">
            <dct:format xmlns:dct="http://someurl/">some value 3</dct:format>
            <dct:title xmlns:dct="http://someurl/">some text of interest to me</dct:title>
        </rdf:Description>
    </rdf:RDF>
</doc:document>

How do I get the "some text of interest to me" using Python/ETree?

Thanks in advance for any help!

0

1 Answer 1

1

You'll need to look for the title element by specifying the namespace:

tree.find('.//dct:title', namespaces={'dct': 'http://purl.org/dc/terms/'})

You have to pass in a namespaces mapping on each search, so you could also just specify that up front and reuse:

nsmap = {
    'dct': 'http://purl.org/dc/terms/',
    'doc': 'http://www.witbd.org/xmlns/common/document/',
    'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
}

tree.find('.//dct:title', namespaces=nsmap)

For your example document (with the namespaces restored), that gives:

>>> tree.find('.//dct:title', namespaces=nsmap)
<Element '{http://purl.org/dc/terms/}title' at 0x105ec4690>
>>> tree.find('.//dct:title', namespaces=nsmap).text
'some text of interest to me'

You could also use the namespace in an XPath expression:

tree.find('.//{http://purl.org/dc/terms/}title')

which is what using a prefix and the namespaces map does internally anyway.

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

1 Comment

BTW this method doesnt work when cElementTree is imported; only with ElementTree

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.