【问题标题】:lxml working with namespaceslxml 使用命名空间
【发布时间】:2016-07-26 14:49:47
【问题描述】:

我正在处理这样一个非常复杂的 XML:

<?xml version="1.0" encoding="UTF-8"?>
<!-- ***** Configuration Data exported at 20160623T110335 ***** -->
<impex:ExportData xmlns:impex="urn:swift:saa:xsd:impex">

<!-- *** Exported Data for Operator *** -->
<OperatorData xmlns="urn:swift:saa:xsd:impex:operator">

<ns2:OperatorDefinition xmlns="urn:swift:saa:xsd:operatorprofile" xmlns:ns2="urn:swift:saa:xsd:impex:operator" xmlns:ns3="urn:swift:saa:xsd:unit" xmlns:ns4="urn:swift:saa:xsd:licenseddestination" xmlns:ns5="urn:swift:saa:xsd:operator" xmlns:ns6="urn:swift:saa:xsd:authenticationservergroup">
    <ns2:Operator>
        <ns5:Identifier>
            <ns5:Name>jdoe</ns5:Name>
        </ns5:Identifier>
        <ns5:Description>John Doe</ns5:Description>
        <ns5:OperatorType>HUMAN</ns5:OperatorType>
        <ns5:AuthenticationType>LDAP</ns5:AuthenticationType>
        <ns5:AuthenticationServerGroup>
            <ns6:Type>LDAP</ns6:Type>
            <ns6:Name>LDAP_GROUP1</ns6:Name>
        </ns5:AuthenticationServerGroup>
        <ns5:LdapUserId>jdoe</ns5:LdapUserId>
        <ns5:Profile>
            <Name>DEV Users</Name>
        </ns5:Profile>
        <ns5:Unit>
            <ns3:Name>None</ns3:Name>
        </ns5:Unit>
    </ns2:Operator>
</ns2:OperatorDefinition>

</OperatorData>

</impex:ExportData>

在这个 XML 中有许多 &lt;ns2:OperatorDefinition&gt; 元素,就像我包含的那个一样。我很难理解如何使用 lxml 提取 &lt;ns5:Description&gt; 之类的东西。我发现的所有命名空间示例都没有这么复杂。

我试图简单地找到标签做这样的事情 -

from lxml import etree
doc = etree.parse('c:/robin/Operators_out.xml')

r = doc.xpath('/x:OperatorData/ns2:OperatorDefinition', namespaces={'x': 'urn:swift:saa:xsd:impex:operator'})
print len(r)
print r[0].text
print r[0].tag

我收到Undefined namespace prefix。

【问题讨论】:

  • 您得到“未定义的命名空间前缀”,因为您没有在 namespaces 字典中包含 ns2 前缀的定义。

标签: python python-2.7 lxml


【解决方案1】:

您的用例可能不需要命名空间,remove them 以使解析更容易:

from lxml import etree, objectify

tree = etree.parse("input.xml")
root = tree.getroot()

# remove namespaces ----
for elem in root.getiterator():
    if not hasattr(elem.tag, 'find'): continue
    i = elem.tag.find('}')
    if i >= 0:
        elem.tag = elem.tag[i+1:]

objectify.deannotate(root, cleanup_namespaces=True)
# ----

name = root.findtext(".//OperatorDefinition/Operator/Identifier/Name")
print(name)

打印jdoe。

【讨论】:

  • 这适用于单个用户我试图弄清楚如果有多个 OperatorDefinitions 具有相同的标签,如何循环它? IE。我要回jdoe、asmith等。
  • @whoiearth 好的,请执行.//OperatorDefinition/Operator/Identifier/Name/text()。
  • @alecse 我最终做了这个并且它有效 - for elem in tree.iterfind('.//OperatorDefinition'): print elem.findtext(".//Operator/Identifier/Name")
猜你喜欢
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多