python - 如何使用ElementTree按属性值查找xml元素

标签 python xml xliff

尝试解析 XML具有 namespace 和属性。我希望通过给定属性 ( id ) 检索元素。

文档指定但是

[@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.

当给定属性名称和值或仅给定属性名称时,以下解决方案都不会返回元素

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>

最佳答案

我不知道如何使用 {None: "urn:oasis:names:tc:xliff:document:1.2"} 来做到这一点root.nsmap 的命名空间...

但是,如果您重新定义 namespace 映射,例如

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

然后就可以了

root.find('.//n:trans-unit[@id="111"]', ns)

关于python - 如何使用ElementTree按属性值查找xml元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53454903/

相关文章:

python - 如何从 Django 中的 auth_user 表访问自定义列?

python - 有没有办法从某一列开始使用枚举?

java - 本地化 xliff 错误消息

symfony - 我应该在 Symfony 2 中使用什么作为 XLIFF 原始文件?

ios - 如何在 Swift 中使用带变量的 NSLocalizedString 函数?

Python 压缩字符串不太正确

python - tensorflow /keras : "logits and labels must have the same first dimension" How to squeeze logits or expand labels?

android - 垂直和水平中心

xml - 对如何使用 JAXB XML 适配器满足我的要求感到困惑

html - 在 HTML 页面中使用引文本体