Python:ElementTree,获取元素的名称空间字符串 [英] Python: ElementTree, get the namespace string of an Element
问题描述
此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>
如果我加载example.xml并使用ElementTree对其进行解析,我可以看到其命名空间为 http://maven.apache.org/POM/4.0.0
。
If I load example.xml and parse it with ElementTree I can see its namespace is 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>
我还没有找到一种方法来从获取名称空间元素
,而无需解析元素的 str(an_element)
。似乎必须有更好的方法。
I have not found a method to call to get just the namespace from an Element
without resorting to parsing the str(an_element)
of an Element. It seems like there got to be a better way.
推荐答案
名称空间应位于 Element.tag
就在实际标记之前:
The namespace should be in Element.tag
right before the "actual" tag:
>>> root = tree.getroot()
>>> root.tag
'{http://maven.apache.org/POM/4.0.0}project'
要了解有关名称空间的更多信息,请查看 ElementTree:使用名称空间和合格名称名称。
To know more about namespaces, take a look at ElementTree: Working with Namespaces and Qualified Names.
这篇关于Python:ElementTree,获取元素的名称空间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!