1

Attempting to parse an XML with namespaces and attributes. I wish to retrieve an element by a given attribute (id).

Documentation specifies but

[@attrib] Selects all elements that have the given attribute.

[@attrib='value'] Selects all elements for which the given attribute has the given value. The value cannot contain quotes.

neither solutions below returns an element when given an attribute name & value or when given an attribute name only

from lxml import etree
tree = etree.parse("es.xml")
root = tree.getroot()

print root.findall('file/body/trans-unit', root.nsmap)


# Unable to fetch all with attribute == id
print root.findall('file/body/trans-unit[@id]', root.nsmap)

# Unable to fetch element with id = 111
print root.find('file/body/trans-unit[@id="111"]', root.nsmap)

XML

<?xml version="1.0" encoding="UTF-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file original="PDDDD" source-language="en" datatype="plaintext" target-language="es">
<header>
<tool tool-id="com.apple.dt.xcode" tool-name="Xcode" tool-version="10.1" build-num="10B61"/>
</header>
<body>
<trans-unit id="111">
<source>Welcome!</source>
<target>Welcome!</target>
<note>Class = "UILabel"; text = "Welcome!"; ObjectID = "7oz-Od-KDt";</note>
</trans-unit>
</body>
</file>
</xliff>
0

1 Answer 1

0

I don't know how to do it with the {None: "urn:oasis:names:tc:xliff:document:1.2"} namespace of root.nsmap...

However, if you redefine a namespace map like

ns = {"n": "urn:oasis:names:tc:xliff:document:1.2"}

then this works

root.find('.//n:trans-unit[@id="111"]', ns)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.