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:使用命名空间和限定名称.
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)
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)
不使用正则表达式:
>>> 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)
| 归档时间: |
|
| 查看次数: |
27047 次 |
| 最近记录: |