Python:ElementTree,获取Element的命名空间字符串

Del*_*ted 20 python elementtree

此XML文件命名为example.xml:

<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>14.0.0</modelVersion>
  <groupId>.com.foobar.flubber</groupId>
  <artifactId>uberportalconf</artifactId>
  <version>13-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>Environment for UberPortalConf</name>
  <description>This is the description</description>    
  <properties>
      <birduberportal.version>11</birduberportal.version>
      <promotiondevice.version>9</promotiondevice.version>
      <foobarportal.version>6</foobarportal.version>
      <eventuberdevice.version>2</eventuberdevice.version>
  </properties>
  <!-- A lot more here, but as it is irrelevant for the problem I have removed it -->
</project>
Run Code Online (Sandbox Code Playgroud)

如果我加载example.xml并使用ElementTree解析它,我可以看到它的命名空间http://maven.apache.org/POM/4.0.0.

>>> from xml.etree import ElementTree
>>> tree = ElementTree.parse('example.xml')
>>> print tree.getroot()
<Element '{http://maven.apache.org/POM/4.0.0}project' at 0x26ee0f0>
Run Code Online (Sandbox Code Playgroud)

我还没有找到一种方法来调用从而Element无需解析str(an_element)元素来获取命名空间.似乎必须有更好的方法.

Rik*_*ggi 22

命名空间应位于Element.tag"实际"标记之前:

>>> root = tree.getroot()
>>> root.tag
'{http://maven.apache.org/POM/4.0.0}project'
Run Code Online (Sandbox Code Playgroud)

要了解有关命名空间的更多信息,请查看ElementTree:使用命名空间和限定名称.

  • 您提供的链接已失效,您可能需要对其进行编辑以指向此信息的替代来源。 (2认同)

Mar*_*som 14

这是正则表达式的完美任务.

import re

def namespace(element):
    m = re.match(r'\{.*\}', element.tag)
    return m.group(0) if m else ''
Run Code Online (Sandbox Code Playgroud)

  • 经过一段时间的争论,这是我找到的最好的解决方案.我无法相信API不会让你找到命名空间的方法,同时,在执行'rootElement.keys()'时它不会返回属性'xmlns'.当然有充分的理由,但我现在找不到它. (10认同)

Jak*_*cil 12

我不确定这是否可行xml.etree,但以下是你如何做到这一点lxml.etree:

>>> from lxml import etree
>>> tree = etree.parse('example.xml')
>>> tree.xpath('namespace-uri(.)')
'http://maven.apache.org/POM/4.0.0'
Run Code Online (Sandbox Code Playgroud)

  • 对于`lxml`来说,获取命名空间的一种更简单的方法是`tree.getroot()。nsmap` (2认同)

Lor*_*can 8

不使用正则表达式:

>>> root
<Element '{http://www.google.com/schemas/sitemap/0.84}urlset' at 0x2f7cc10>

>>> root.tag.split('}')[0].strip('{')
'http://www.google.com/schemas/sitemap/0.84'
Run Code Online (Sandbox Code Playgroud)